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
|
google__dagger
|
javatests/dagger/functional/builder/BuilderTest.java
|
{
"start": 11225,
"end": 11309
}
|
interface ____ {
int i();
String s();
@Subcomponent.Builder
|
Grandchild
|
java
|
apache__flink
|
flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/GlobalStreamImpl.java
|
{
"start": 12775,
"end": 13797
}
|
class ____<OUT1, OUT2> implements TwoGlobalStreams<OUT1, OUT2> {
private final GlobalStreamImpl<OUT1> firstStream;
private final GlobalStreamImpl<OUT2> secondStream;
public static <OUT1, OUT2> TwoGlobalStreamsImpl<OUT1, OUT2> of(
GlobalStreamImpl<OUT1> firstStream, GlobalStreamImpl<OUT2> secondStream) {
return new TwoGlobalStreamsImpl<>(firstStream, secondStream);
}
private TwoGlobalStreamsImpl(
GlobalStreamImpl<OUT1> firstStream, GlobalStreamImpl<OUT2> secondStream) {
this.firstStream = firstStream;
this.secondStream = secondStream;
}
@Override
public ProcessConfigurableAndGlobalStream<OUT1> getFirst() {
return StreamUtils.wrapWithConfigureHandle(firstStream);
}
@Override
public ProcessConfigurableAndGlobalStream<OUT2> getSecond() {
return StreamUtils.wrapWithConfigureHandle(secondStream);
}
}
}
|
TwoGlobalStreamsImpl
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/issues/OnExceptionBeforeErrorHandlerIssueTest.java
|
{
"start": 1039,
"end": 3473
}
|
class ____ extends ContextTestSupport {
@Test
public void testOk() throws Exception {
context.getRouteController().startRoute("foo");
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testKaboom() throws Exception {
context.getRouteController().startRoute("foo");
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody("direct:start", "kaboom");
assertMockEndpointsSatisfied();
}
@Test
public void testIllegal() throws Exception {
context.getRouteController().startRoute("foo");
getMockEndpoint("mock:error").expectedMessageCount(1);
getMockEndpoint("mock:dead").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody("direct:start", "illegal");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(IllegalArgumentException.class).handled(true).setBody().constant("Handled").to("mock:error").end();
// usually error handler should be defined first (before
// onException),
// but its not enforced
errorHandler(deadLetterChannel("mock:dead").useOriginalMessage());
from("direct:start").routeId("foo").autoStartup(false).process(new Processor() {
public void process(Exchange exchange) {
String body = exchange.getIn().getBody(String.class);
if ("illegal".equals(body)) {
throw new IllegalArgumentException("I cannot do this");
} else if ("kaboom".equals(body)) {
throw new RuntimeException("Kaboom");
}
}
}).to("mock:result");
}
};
}
}
|
OnExceptionBeforeErrorHandlerIssueTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/indices/NodeIndicesStats.java
|
{
"start": 2906,
"end": 12954
}
|
class ____ implements Writeable, ChunkedToXContent {
private static final TransportVersion VERSION_SUPPORTING_STATS_BY_INDEX = TransportVersions.V_8_5_0;
private static final TransportVersion NODES_STATS_SUPPORTS_MULTI_PROJECT = TransportVersion.fromName(
"nodes_stats_supports_multi_project"
);
private static final Map<Index, List<IndexShardStats>> EMPTY_STATS_BY_SHARD = Map.of();
private final CommonStats stats;
private final Map<Index, List<IndexShardStats>> statsByShard;
private final Map<Index, CommonStats> statsByIndex;
private final Map<Index, ProjectId> projectsByIndex;
public NodeIndicesStats(StreamInput in) throws IOException {
stats = new CommonStats(in);
statsByShard = new HashMap<>();
int entries = in.readVInt();
for (int i = 0; i < entries; i++) {
Index index = new Index(in);
int indexShardListSize = in.readVInt();
List<IndexShardStats> indexShardStats = new ArrayList<>(indexShardListSize);
for (int j = 0; j < indexShardListSize; j++) {
indexShardStats.add(new IndexShardStats(in));
}
statsByShard.put(index, indexShardStats);
}
if (in.getTransportVersion().onOrAfter(VERSION_SUPPORTING_STATS_BY_INDEX)) {
statsByIndex = in.readMap(Index::new, CommonStats::new);
} else {
statsByIndex = new HashMap<>();
}
if (in.getTransportVersion().supports(NODES_STATS_SUPPORTS_MULTI_PROJECT)) {
projectsByIndex = in.readMap(Index::new, ProjectId::readFrom);
} else {
// Older nodes do not include the index-to-project map, so we leave it empty. This means all indices will be treated as if the
// project is unknown. This does not matter as the map is only used in multi-project clusters which will not have old nodes.
projectsByIndex = Map.of();
}
}
public NodeIndicesStats(
CommonStats oldStats,
Map<Index, CommonStats> statsByIndex,
Map<Index, List<IndexShardStats>> statsByShard,
Map<Index, ProjectId> projectsByIndex,
boolean includeShardsStats
) {
if (includeShardsStats) {
this.statsByShard = requireNonNull(statsByShard);
} else {
this.statsByShard = EMPTY_STATS_BY_SHARD;
}
this.statsByIndex = requireNonNull(statsByIndex);
// make a total common stats from old ones and current ones
this.stats = oldStats;
for (List<IndexShardStats> shardStatsList : statsByShard.values()) {
for (IndexShardStats indexShardStats : shardStatsList) {
for (ShardStats shardStats : indexShardStats.getShards()) {
stats.add(shardStats.getStats());
}
}
}
for (CommonStats indexStats : statsByIndex.values()) {
stats.add(indexStats);
}
this.projectsByIndex = requireNonNull(projectsByIndex);
}
@Nullable
public StoreStats getStore() {
return stats.getStore();
}
@Nullable
public DocsStats getDocs() {
return stats.getDocs();
}
@Nullable
public IndexingStats getIndexing() {
return stats.getIndexing();
}
@Nullable
public GetStats getGet() {
return stats.getGet();
}
@Nullable
public SearchStats getSearch() {
return stats.getSearch();
}
@Nullable
public MergeStats getMerge() {
return stats.getMerge();
}
@Nullable
public RefreshStats getRefresh() {
return stats.getRefresh();
}
@Nullable
public FlushStats getFlush() {
return stats.getFlush();
}
@Nullable
public WarmerStats getWarmer() {
return stats.getWarmer();
}
@Nullable
public FieldDataStats getFieldData() {
return stats.getFieldData();
}
@Nullable
public QueryCacheStats getQueryCache() {
return stats.getQueryCache();
}
@Nullable
public RequestCacheStats getRequestCache() {
return stats.getRequestCache();
}
@Nullable
public CompletionStats getCompletion() {
return stats.getCompletion();
}
@Nullable
public SegmentsStats getSegments() {
return stats.getSegments();
}
@Nullable
public TranslogStats getTranslog() {
return stats.getTranslog();
}
@Nullable
public RecoveryStats getRecoveryStats() {
return stats.getRecoveryStats();
}
@Nullable
public BulkStats getBulk() {
return stats.getBulk();
}
@Nullable
public ShardCountStats getShardCount() {
return stats.getShards();
}
@Nullable
public NodeMappingStats getNodeMappingStats() {
return stats.getNodeMappings();
}
@Nullable
public DenseVectorStats getDenseVectorStats() {
return stats.getDenseVectorStats();
}
@Nullable
public SparseVectorStats getSparseVectorStats() {
return stats.getSparseVectorStats();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
stats.writeTo(out);
out.writeMap(statsByShard, StreamOutput::writeWriteable, StreamOutput::writeCollection);
if (out.getTransportVersion().onOrAfter(VERSION_SUPPORTING_STATS_BY_INDEX)) {
out.writeMap(statsByIndex);
}
if (out.getTransportVersion().supports(NODES_STATS_SUPPORTS_MULTI_PROJECT)) {
out.writeMap(projectsByIndex);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeIndicesStats that = (NodeIndicesStats) o;
return stats.equals(that.stats)
&& statsByShard.equals(that.statsByShard)
&& statsByIndex.equals(that.statsByIndex)
&& projectsByIndex.equals(that.projectsByIndex);
}
@Override
public int hashCode() {
return Objects.hash(stats, statsByShard, statsByIndex, projectsByIndex);
}
@Override
public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params outerParams) {
return Iterators.concat(
Iterators.single((builder, params) -> {
builder.startObject(Fields.INDICES);
return stats.toXContent(builder, outerParams);
}),
switch (NodeStatsLevel.of(outerParams, NodeStatsLevel.NODE)) {
case NODE -> Collections.<ToXContent>emptyIterator();
case INDICES -> ChunkedToXContentHelper.object(
Fields.INDICES,
Iterators.map(createCommonStatsByIndex().entrySet().iterator(), entry -> (builder, params) -> {
builder.startObject(xContentKey(entry.getKey(), outerParams));
entry.getValue().toXContent(builder, outerParams);
return builder.endObject();
})
);
case SHARDS -> ChunkedToXContentHelper.object(
Fields.SHARDS,
Iterators.flatMap(
statsByShard.entrySet().iterator(),
entry -> ChunkedToXContentHelper.array(
xContentKey(entry.getKey(), outerParams),
Iterators.flatMap(
entry.getValue().iterator(),
indexShardStats -> Iterators.concat(
Iterators.single(
(b, p) -> b.startObject().startObject(String.valueOf(indexShardStats.getShardId().getId()))
),
Iterators.flatMap(Iterators.forArray(indexShardStats.getShards()), Iterators::<ToXContent>single),
Iterators.single((b, p) -> b.endObject().endObject())
)
)
)
)
);
},
ChunkedToXContentHelper.endObject()
);
}
private String xContentKey(Index index, ToXContent.Params outerParams) {
if (outerParams.paramAsBoolean(NodeStats.MULTI_PROJECT_ENABLED_XCONTENT_PARAM_KEY, false)) {
ProjectId projectId = projectsByIndex.get(index);
if (projectId == null) {
// This can happen if the stats were captured after the IndexService was created but before the state was updated.
// The best we can do is handle it gracefully. We include the UUID as well as the name to ensure it is unambiguous.
return "<unknown>/" + index.getName() + "/" + index.getUUID();
} else {
return projectId + "/" + index.getName();
}
} else {
return index.getName();
}
}
private Map<Index, CommonStats> createCommonStatsByIndex() {
Map<Index, CommonStats> statsMap = new HashMap<>();
for (Map.Entry<Index, List<IndexShardStats>> entry : statsByShard.entrySet()) {
if (statsMap.containsKey(entry.getKey()) == false) {
statsMap.put(entry.getKey(), new CommonStats());
}
for (IndexShardStats indexShardStats : entry.getValue()) {
for (ShardStats shardStats : indexShardStats.getShards()) {
statsMap.get(entry.getKey()).add(shardStats.getStats());
}
}
}
for (Map.Entry<Index, CommonStats> entry : statsByIndex.entrySet()) {
statsMap.computeIfAbsent(entry.getKey(), k -> new CommonStats()).add(entry.getValue());
}
return statsMap;
}
public List<IndexShardStats> getShardStats(Index index) {
return statsByShard.get(index);
}
static final
|
NodeIndicesStats
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/type/ClassStack.java
|
{
"start": 129,
"end": 267
}
|
class ____ to keep track of 'call stack' for classes being referenced
* (as well as unbound variables)
*
* @since 2.7
*/
public final
|
used
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java
|
{
"start": 17881,
"end": 18125
}
|
class ____ {
public static void main() {
new SpringApplication(ConfigWithPublicMain.class).run("--spring.profiles.active=frommain");
}
}
@SpringBootConfiguration(proxyBeanMethods = false)
public static
|
ConfigWithPublicParameterlessMain
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/DeleteMultiLevelOrphansTest.java
|
{
"start": 885,
"end": 8930
}
|
class ____ {
@BeforeEach
public void createData(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Preisregelung preisregelung = new Preisregelung();
Tranchenmodell tranchenmodell = new Tranchenmodell();
X x = new X();
Tranche tranche1 = new Tranche();
Y y = new Y();
Tranche tranche2 = new Tranche();
preisregelung.setTranchenmodell( tranchenmodell );
tranchenmodell.setPreisregelung( preisregelung );
tranchenmodell.setX( x );
x.setTranchenmodell( tranchenmodell );
tranchenmodell.getTranchen().add( tranche1 );
tranche1.setTranchenmodell( tranchenmodell );
tranchenmodell.getTranchen().add( tranche2 );
tranche2.setTranchenmodell( tranchenmodell );
tranche1.setY( y );
y.setTranche( tranche1 );
entityManager.persist( preisregelung );
} );
}
@AfterEach
public void cleanupData(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> scope.getEntityManagerFactory().getSchemaManager().truncate() );
}
@Test
@JiraKey( value = "HHH-9091")
public void testDirectAssociationOrphanedWhileManaged(EntityManagerFactoryScope scope) {
Long id = scope.fromTransaction(
em -> {
List results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
Preisregelung preisregelung = (Preisregelung) results.get( 0 );
Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell();
assertNotNull( tranchenmodell );
assertNotNull( tranchenmodell.getX() );
assertEquals( 2, tranchenmodell.getTranchen().size() );
assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() );
preisregelung.setTranchenmodell( null );
return preisregelung.getId();
}
);
scope.inTransaction(
em -> {
Preisregelung preisregelung = em.find( Preisregelung.class, id );
assertNull( preisregelung.getTranchenmodell() );
List results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Tranche" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from X" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Y" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
}
);
}
@Test
@JiraKey( value = "HHH-9091")
public void testReplacedDirectAssociationWhileManaged(EntityManagerFactoryScope scope) {
EntityManager em = scope.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
List results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
Preisregelung preisregelung = (Preisregelung) results.get( 0 );
Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell();
assertNotNull( tranchenmodell );
assertNotNull( tranchenmodell.getX() );
assertEquals( 2, tranchenmodell.getTranchen().size() );
assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() );
// Create a new Tranchenmodell with new direct and nested associations
Tranchenmodell tranchenmodellNew = new Tranchenmodell();
X xNew = new X();
tranchenmodellNew.setX( xNew );
xNew.setTranchenmodell( tranchenmodellNew );
Tranche trancheNew = new Tranche();
tranchenmodellNew.getTranchen().add( trancheNew );
trancheNew.setTranchenmodell( tranchenmodellNew );
Y yNew = new Y();
trancheNew.setY( yNew );
yNew.setTranche( trancheNew );
// Replace with a new Tranchenmodell instance containing new direct and nested associations
preisregelung.setTranchenmodell(tranchenmodellNew );
tranchenmodellNew.setPreisregelung( preisregelung );
em.getTransaction().commit();
em.close();
em = scope.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
results = em.createQuery( "from Tranche" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from X" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Y" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
preisregelung = (Preisregelung) results.get( 0 );
tranchenmodell = preisregelung.getTranchenmodell();
assertNotNull( tranchenmodell );
assertEquals( tranchenmodellNew.getId(), tranchenmodell.getId() );
assertNotNull( tranchenmodell.getX() );
assertEquals( xNew.getId(), tranchenmodell.getX().getId() );
assertEquals( 1, tranchenmodell.getTranchen().size() );
assertEquals( trancheNew.getId(), tranchenmodell.getTranchen().get( 0 ).getId() );
assertEquals( yNew.getId(), tranchenmodell.getTranchen().get( 0 ).getY().getId() );
// Replace with a new Tranchenmodell instance with no associations
tranchenmodellNew = new Tranchenmodell();
preisregelung.setTranchenmodell(tranchenmodellNew );
tranchenmodellNew.setPreisregelung( preisregelung );
em.getTransaction().commit();
em.close();
em = scope.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 1, results.size() );
tranchenmodell = (Tranchenmodell) results.get( 0 );
assertEquals( tranchenmodellNew.getId(), tranchenmodell.getId() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
preisregelung = (Preisregelung) results.get( 0 );
assertEquals( tranchenmodell, preisregelung.getTranchenmodell() );
results = em.createQuery( "from Tranche" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from X" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Y" ).getResultList();
assertEquals( 0, results.size() );
em.getTransaction().commit();
em.close();
}
@Test
@JiraKey( value = "HHH-9091")
public void testDirectAndNestedAssociationsOrphanedWhileManaged(EntityManagerFactoryScope scope) {
Long id = scope.fromTransaction(
em -> {
List results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 1, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
Preisregelung preisregelung = (Preisregelung) results.get( 0 );
Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell();
assertNotNull( tranchenmodell );
assertNotNull( tranchenmodell.getX() );
assertEquals( 2, tranchenmodell.getTranchen().size() );
assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() );
preisregelung.setTranchenmodell( null );
tranchenmodell.setX( null );
tranchenmodell.getTranchen().get( 0 ).setY( null );
return preisregelung.getId();
}
);
scope.inTransaction(
em -> {
Preisregelung preisregelung = em.find( Preisregelung.class, id );
assertNull( preisregelung.getTranchenmodell() );
List results = em.createQuery( "from Tranchenmodell" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Tranche" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from X" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Y" ).getResultList();
assertEquals( 0, results.size() );
results = em.createQuery( "from Preisregelung" ).getResultList();
assertEquals( 1, results.size() );
}
);
}
}
|
DeleteMultiLevelOrphansTest
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
|
{
"start": 38300,
"end": 38895
}
|
class ____ fallback
if (mbd.getInstanceSupplier() == null) {
result = getFactoryBeanGeneric(mbd.targetType);
if (result.resolve() != null) {
return result;
}
result = getFactoryBeanGeneric(mbd.hasBeanClass() ? ResolvableType.forClass(mbd.getBeanClass()) : null);
if (result.resolve() != null) {
return result;
}
}
// FactoryBean type not resolvable
return ResolvableType.NONE;
}
/**
* Introspect the factory method signatures on the given bean class,
* trying to find a common {@code FactoryBean} object type declared there.
* @param beanClass the bean
|
as
|
java
|
apache__kafka
|
streams/test-utils/src/main/java/org/apache/kafka/streams/processor/api/MockProcessorContext.java
|
{
"start": 17726,
"end": 20551
}
|
interface ____ assumed by state stores that add change-logging.
// Rather than risk a mysterious ClassCastException during unit tests, throw an explanatory exception.
throw new UnsupportedOperationException(
"MockProcessorContext does not provide record collection. " +
"For processor unit tests, use an in-memory state store with change-logging disabled. " +
"Alternatively, use the TopologyTestDriver for testing processor/store/topology integration."
);
}
/**
* Used to get a {@link StateStoreContext} for use with
* {@link StateStore#init(StateStoreContext, StateStore)}
* if you need to initialize a store for your tests.
* @return a {@link StateStoreContext} that delegates to this ProcessorContext.
*/
public StateStoreContext getStateStoreContext() {
return new StateStoreContext() {
@Override
public String applicationId() {
return MockProcessorContext.this.applicationId();
}
@Override
public TaskId taskId() {
return MockProcessorContext.this.taskId();
}
@Override
public Optional<RecordMetadata> recordMetadata() {
return MockProcessorContext.this.recordMetadata();
}
@Override
public Serde<?> keySerde() {
return MockProcessorContext.this.keySerde();
}
@Override
public Serde<?> valueSerde() {
return MockProcessorContext.this.valueSerde();
}
@Override
public File stateDir() {
return MockProcessorContext.this.stateDir();
}
@Override
public StreamsMetrics metrics() {
return MockProcessorContext.this.metrics();
}
@Override
public void register(final StateStore store,
final StateRestoreCallback stateRestoreCallback) {
register(store, stateRestoreCallback, () -> { });
}
@Override
public void register(final StateStore store,
final StateRestoreCallback stateRestoreCallback,
final CommitCallback checkpoint) {
stateStores.put(store.name(), store);
}
@Override
public Map<String, Object> appConfigs() {
return MockProcessorContext.this.appConfigs();
}
@Override
public Map<String, Object> appConfigsWithPrefix(final String prefix) {
return MockProcessorContext.this.appConfigsWithPrefix(prefix);
}
};
}
}
|
is
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/ReadOp.java
|
{
"start": 1858,
"end": 5136
}
|
class ____ extends Operation {
private static final Logger LOG = LoggerFactory.getLogger(ReadOp.class);
ReadOp(ConfigExtractor cfg, Random rnd) {
super(ReadOp.class.getSimpleName(), cfg, rnd);
}
/**
* Gets the file name to read
*
* @return Path
*/
protected Path getReadFile() {
Path fn = getFinder().getFile();
return fn;
}
@Override // Operation
List<OperationOutput> run(FileSystem fs) {
List<OperationOutput> out = super.run(fs);
DataInputStream is = null;
try {
Path fn = getReadFile();
Range<Long> readSizeRange = getConfig().getReadSize();
long readSize = 0;
String readStrAm = "";
if (getConfig().shouldReadFullFile()) {
readSize = Long.MAX_VALUE;
readStrAm = "full file";
} else {
readSize = Range.betweenPositive(getRandom(), readSizeRange);
readStrAm = Helper.toByteInfo(readSize);
}
long timeTaken = 0;
long chunkSame = 0;
long chunkDiff = 0;
long bytesRead = 0;
long startTime = 0;
DataVerifier vf = new DataVerifier();
LOG.info("Attempting to read file at " + fn + " of size (" + readStrAm
+ ")");
{
// open
startTime = Timer.now();
is = fs.open(fn);
timeTaken += Timer.elapsed(startTime);
// read & verify
VerifyOutput vo = vf.verifyFile(readSize, is);
timeTaken += vo.getReadTime();
chunkSame += vo.getChunksSame();
chunkDiff += vo.getChunksDifferent();
bytesRead += vo.getBytesRead();
// capture close time
startTime = Timer.now();
is.close();
is = null;
timeTaken += Timer.elapsed(startTime);
}
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.OK_TIME_TAKEN, timeTaken));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.BYTES_READ, bytesRead));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.SUCCESSES, 1L));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.CHUNKS_VERIFIED, chunkSame));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.CHUNKS_UNVERIFIED, chunkDiff));
LOG.info("Read " + Helper.toByteInfo(bytesRead) + " of " + fn + " with "
+ chunkSame + " chunks being same as expected and " + chunkDiff
+ " chunks being different than expected in " + timeTaken
+ " milliseconds");
} catch (FileNotFoundException e) {
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.NOT_FOUND, 1L));
LOG.warn("Error with reading", e);
} catch (BadFileException e) {
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.BAD_FILES, 1L));
LOG.warn("Error reading bad file", e);
} catch (IOException e) {
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.FAILURES, 1L));
LOG.warn("Error reading", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOG.warn("Error closing read stream", e);
}
}
}
return out;
}
}
|
ReadOp
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/ThreeLetterTimeZoneID.java
|
{
"start": 1745,
"end": 6943
}
|
class ____ extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> METHOD_MATCHER =
MethodMatchers.staticMethod()
.onClass("java.util.TimeZone")
.named("getTimeZone")
.withParameters("java.lang.String");
private static final Matcher<ExpressionTree> JODATIME_METHOD_MATCHER =
MethodMatchers.staticMethod()
.onClass("org.joda.time.DateTimeZone")
.named("forTimeZone")
.withParameters("java.util.TimeZone");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!METHOD_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
String value = ASTHelpers.constValue(tree.getArguments().getFirst(), String.class);
if (value == null) {
// Value isn't a compile-time constant, so we can't know if it's unsafe.
return Description.NO_MATCH;
}
Replacement replacement = getReplacement(value, isInJodaTimeContext(state), message());
if (replacement.replacements.isEmpty()) {
return Description.NO_MATCH;
}
Description.Builder builder = buildDescription(tree).setMessage(replacement.message);
for (String r : replacement.replacements) {
builder.addFix(
SuggestedFix.replace(tree.getArguments().getFirst(), state.getConstantExpression(r)));
}
return builder.build();
}
@VisibleForTesting
static Replacement getReplacement(String id, boolean inJodaTimeContext, String message) {
switch (id) {
case "EST" -> {
return handleNonDaylightSavingsZone(
inJodaTimeContext, "America/New_York", "Etc/GMT+5", message);
}
case "HST" -> {
return handleNonDaylightSavingsZone(
inJodaTimeContext, "Pacific/Honolulu", "Etc/GMT+10", message);
}
case "MST" -> {
return handleNonDaylightSavingsZone(
inJodaTimeContext, "America/Denver", "Etc/GMT+7", message);
}
default -> {}
}
String zoneIdReplacement = ZoneId.SHORT_IDS.get(id);
if (zoneIdReplacement == null) {
return Replacement.NO_REPLACEMENT;
}
if (id.endsWith("ST")) {
TimeZone timeZone = TimeZone.getTimeZone(id);
if (timeZone.observesDaylightTime()) {
// Make sure that the offset is a whole number of hours; otherwise, there is no Etc/GMT+X
// zone. Custom time zones don't need to be handled.
long hours = Duration.ofMillis(timeZone.getRawOffset()).toHours();
long millis = Duration.ofHours(hours).toMillis();
if (millis == timeZone.getRawOffset()) {
// This is a "X Standard Time" zone, but it observes daylight savings.
// Suggest the equivalent zone, as well as a fixed zone at the non-daylight savings
// offset.
String fixedOffset = String.format("Etc/GMT%+d", -hours);
String newDescription =
message
+ "\n\n"
+ observesDaylightSavingsMessage("TimeZone", zoneIdReplacement, fixedOffset);
return new Replacement(newDescription, ImmutableList.of(zoneIdReplacement, fixedOffset));
}
}
}
return new Replacement(message, ImmutableList.of(zoneIdReplacement));
}
// American time zones for which the TLA doesn't observe daylight savings.
// https://www-01.ibm.com/support/docview.wss?uid=swg21250503#3char
// How we handle it depends upon whether we are in a JodaTime context or not.
static Replacement handleNonDaylightSavingsZone(
boolean inJodaTimeContext, String daylightSavingsZone, String fixedOffset, String message) {
if (inJodaTimeContext) {
String newDescription =
message
+ "\n\n"
+ observesDaylightSavingsMessage("DateTimeZone", daylightSavingsZone, fixedOffset);
return new Replacement(newDescription, ImmutableList.of(daylightSavingsZone, fixedOffset));
} else {
String newDescription =
message
+ "\n\n"
+ "This TimeZone will not observe daylight savings. "
+ "If this is intended, use "
+ fixedOffset
+ " instead; to observe daylight savings, use "
+ daylightSavingsZone
+ ".";
return new Replacement(newDescription, ImmutableList.of(fixedOffset, daylightSavingsZone));
}
}
private static String observesDaylightSavingsMessage(
String type, String daylightSavingsZone, String fixedOffset) {
return "This "
+ type
+ " will observe daylight savings. "
+ "If this is intended, use "
+ daylightSavingsZone
+ " instead; otherwise use "
+ fixedOffset
+ ".";
}
private static boolean isInJodaTimeContext(VisitorState state) {
if (state.getPath().getParentPath() != null) {
Tree parentLeaf = state.getPath().getParentPath().getLeaf();
if (parentLeaf instanceof ExpressionTree expressionTree
&& JODATIME_METHOD_MATCHER.matches(expressionTree, state)) {
return true;
}
}
return false;
}
@VisibleForTesting
static final
|
ThreeLetterTimeZoneID
|
java
|
apache__flink
|
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/NFASerializerUpgradeTest.java
|
{
"start": 12092,
"end": 13292
}
|
class ____
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<SharedBufferNode> {
@Override
public TypeSerializer<SharedBufferNode> createUpgradedSerializer() {
return new SharedBufferNodeSerializer();
}
@Override
public Condition<SharedBufferNode> testDataCondition() {
SharedBufferNode result = new SharedBufferNode();
result.addEdge(
new SharedBufferEdge(
new NodeId(new EventId(42, 42L), "page"), new DeweyNumber(42)));
return new Condition<>(value -> value.equals(result), "");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<SharedBufferNode>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "nfa-state-serializer"
// ----------------------------------------------------------------------------------------------
/**
* This
|
SharedBufferNodeSerializerVerifier
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariant.java
|
{
"start": 3127,
"end": 18594
}
|
class ____ implements Variant {
private final byte[] value;
private final byte[] metadata;
// The variant value doesn't use the whole `value` binary, but starts from its `pos` index and
// spans a size of `valueSize(value, pos)`. This design avoids frequent copies of the value
// binary when reading a sub-variant in the array/object element.
private final int pos;
public BinaryVariant(byte[] value, byte[] metadata) {
this(value, metadata, 0);
}
private BinaryVariant(byte[] value, byte[] metadata, int pos) {
this.value = value;
this.metadata = metadata;
this.pos = pos;
// There is currently only one allowed version.
if (metadata.length < 1 || (metadata[0] & VERSION_MASK) != VERSION) {
throw malformedVariant();
}
// Don't attempt to use a Variant larger than 16 MiB. We'll never produce one, and it risks
// memory instability.
if (metadata.length > SIZE_LIMIT || value.length > SIZE_LIMIT) {
throw variantConstructorSizeLimit();
}
}
@Override
public boolean isPrimitive() {
return !isArray() && !isObject();
}
@Override
public boolean isArray() {
return getType() == Type.ARRAY;
}
@Override
public boolean isObject() {
return getType() == Type.OBJECT;
}
@Override
public boolean isNull() {
return getType() == Type.NULL;
}
@Override
public Type getType() {
return BinaryVariantUtil.getType(value, pos);
}
@Override
public boolean getBoolean() throws VariantTypeException {
checkType(Type.BOOLEAN, getType());
return BinaryVariantUtil.getBoolean(value, pos);
}
@Override
public byte getByte() throws VariantTypeException {
checkType(Type.TINYINT, getType());
return (byte) BinaryVariantUtil.getLong(value, pos);
}
@Override
public short getShort() throws VariantTypeException {
checkType(Type.SMALLINT, getType());
return (short) BinaryVariantUtil.getLong(value, pos);
}
@Override
public int getInt() throws VariantTypeException {
checkType(Type.INT, getType());
return (int) BinaryVariantUtil.getLong(value, pos);
}
@Override
public long getLong() throws VariantTypeException {
checkType(Type.BIGINT, getType());
return BinaryVariantUtil.getLong(value, pos);
}
@Override
public float getFloat() throws VariantTypeException {
checkType(Type.FLOAT, getType());
return BinaryVariantUtil.getFloat(value, pos);
}
@Override
public BigDecimal getDecimal() throws VariantTypeException {
checkType(Type.DECIMAL, getType());
return BinaryVariantUtil.getDecimal(value, pos);
}
@Override
public double getDouble() throws VariantTypeException {
checkType(Type.DOUBLE, getType());
return BinaryVariantUtil.getDouble(value, pos);
}
@Override
public String getString() throws VariantTypeException {
checkType(Type.STRING, getType());
return BinaryVariantUtil.getString(value, pos);
}
@Override
public LocalDate getDate() throws VariantTypeException {
checkType(Type.DATE, getType());
return LocalDate.ofEpochDay(BinaryVariantUtil.getLong(value, pos));
}
@Override
public LocalDateTime getDateTime() throws VariantTypeException {
checkType(Type.TIMESTAMP, getType());
return microsToInstant(BinaryVariantUtil.getLong(value, pos))
.atZone(ZoneOffset.UTC)
.toLocalDateTime();
}
@Override
public Instant getInstant() throws VariantTypeException {
checkType(Type.TIMESTAMP_LTZ, getType());
return microsToInstant(BinaryVariantUtil.getLong(value, pos));
}
@Override
public byte[] getBytes() throws VariantTypeException {
checkType(Type.BYTES, getType());
return BinaryVariantUtil.getBinary(value, pos);
}
@Override
public Object get() throws VariantTypeException {
switch (getType()) {
case NULL:
return null;
case BOOLEAN:
return getBoolean();
case TINYINT:
return getByte();
case SMALLINT:
return getShort();
case INT:
return getInt();
case BIGINT:
return getLong();
case FLOAT:
return getFloat();
case DOUBLE:
return getDouble();
case DECIMAL:
return getDecimal();
case STRING:
return getString();
case DATE:
return getDate();
case TIMESTAMP:
return getDateTime();
case TIMESTAMP_LTZ:
return getInstant();
case BYTES:
return getBytes();
default:
throw new VariantTypeException(
String.format("Expecting a primitive variant but got %s", getType()));
}
}
@Override
public <T> T getAs() throws VariantTypeException {
return (T) get();
}
@Override
public Variant getElement(int index) throws VariantTypeException {
return getElementAtIndex(index);
}
@Override
public Variant getField(String fieldName) throws VariantTypeException {
return getFieldByKey(fieldName);
}
@Override
public String toJson() {
StringBuilder sb = new StringBuilder();
toJsonImpl(value, metadata, pos, sb, ZoneOffset.UTC);
return sb.toString();
}
public byte[] getValue() {
if (pos == 0) {
return value;
}
int size = valueSize(value, pos);
checkIndex(pos + size - 1, value.length);
return Arrays.copyOfRange(value, pos, pos + size);
}
public byte[] getMetadata() {
return metadata;
}
public int getPos() {
return pos;
}
private static void toJsonImpl(
byte[] value, byte[] metadata, int pos, StringBuilder sb, ZoneId zoneId) {
switch (BinaryVariantUtil.getType(value, pos)) {
case OBJECT:
handleObject(
value,
pos,
(size, idSize, offsetSize, idStart, offsetStart, dataStart) -> {
sb.append('{');
for (int i = 0; i < size; ++i) {
int id = readUnsigned(value, idStart + idSize * i, idSize);
int offset =
readUnsigned(
value, offsetStart + offsetSize * i, offsetSize);
int elementPos = dataStart + offset;
if (i != 0) {
sb.append(',');
}
sb.append(escapeJson(getMetadataKey(metadata, id)));
sb.append(':');
toJsonImpl(value, metadata, elementPos, sb, zoneId);
}
sb.append('}');
return null;
});
break;
case ARRAY:
handleArray(
value,
pos,
(size, offsetSize, offsetStart, dataStart) -> {
sb.append('[');
for (int i = 0; i < size; ++i) {
int offset =
readUnsigned(
value, offsetStart + offsetSize * i, offsetSize);
int elementPos = dataStart + offset;
if (i != 0) {
sb.append(',');
}
toJsonImpl(value, metadata, elementPos, sb, zoneId);
}
sb.append(']');
return null;
});
break;
case NULL:
sb.append("null");
break;
case BOOLEAN:
sb.append(BinaryVariantUtil.getBoolean(value, pos));
break;
case TINYINT:
case SMALLINT:
case INT:
case BIGINT:
sb.append(BinaryVariantUtil.getLong(value, pos));
break;
case STRING:
sb.append(escapeJson(BinaryVariantUtil.getString(value, pos)));
break;
case DOUBLE:
sb.append(BinaryVariantUtil.getDouble(value, pos));
break;
case DECIMAL:
sb.append(BinaryVariantUtil.getDecimal(value, pos).toPlainString());
break;
case DATE:
appendQuoted(
sb,
LocalDate.ofEpochDay((int) BinaryVariantUtil.getLong(value, pos))
.toString());
break;
case TIMESTAMP_LTZ:
appendQuoted(
sb,
TIMESTAMP_LTZ_FORMATTER.format(
microsToInstant(BinaryVariantUtil.getLong(value, pos))
.atZone(zoneId)));
break;
case TIMESTAMP:
appendQuoted(
sb,
TIMESTAMP_FORMATTER.format(
microsToInstant(BinaryVariantUtil.getLong(value, pos))
.atZone(ZoneOffset.UTC)));
break;
case FLOAT:
sb.append(BinaryVariantUtil.getFloat(value, pos));
break;
case BYTES:
appendQuoted(
sb,
Base64.getEncoder()
.encodeToString(BinaryVariantUtil.getBinary(value, pos)));
break;
default:
throw unexpectedType(BinaryVariantUtil.getType(value, pos));
}
}
private static Instant microsToInstant(long timestamp) {
return Instant.EPOCH.plus(timestamp, ChronoUnit.MICROS);
}
private void checkType(Type expected, Type actual) {
if (expected != actual) {
throw new VariantTypeException(
String.format("Expected type %s but got %s", expected, actual));
}
}
// Find the field value whose key is equal to `key`. Return null if the key is not found.
// It is only legal to call it when `getType()` is `Type.OBJECT`.
private BinaryVariant getFieldByKey(String key) {
return handleObject(
value,
pos,
(size, idSize, offsetSize, idStart, offsetStart, dataStart) -> {
// Use linear search for a short list. Switch to binary search when the length
// reaches `BINARY_SEARCH_THRESHOLD`.
if (size < BINARY_SEARCH_THRESHOLD) {
for (int i = 0; i < size; ++i) {
int id = readUnsigned(value, idStart + idSize * i, idSize);
if (key.equals(getMetadataKey(metadata, id))) {
int offset =
readUnsigned(
value, offsetStart + offsetSize * i, offsetSize);
return new BinaryVariant(value, metadata, dataStart + offset);
}
}
} else {
int low = 0;
int high = size - 1;
while (low <= high) {
// Use unsigned right shift to compute the middle of `low` and `high`.
// This is not only a performance optimization, because it can properly
// handle the case where `low + high` overflows int.
int mid = (low + high) >>> 1;
int id = readUnsigned(value, idStart + idSize * mid, idSize);
int cmp = getMetadataKey(metadata, id).compareTo(key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
int offset =
readUnsigned(
value, offsetStart + offsetSize * mid, offsetSize);
return new BinaryVariant(value, metadata, dataStart + offset);
}
}
}
return null;
});
}
// Get the array element at the `index` slot. Return null if `index` is out of the bound of
// `[0, arraySize())`.
// It is only legal to call it when `getType()` is `Type.ARRAY`.
private BinaryVariant getElementAtIndex(int index) {
return handleArray(
value,
pos,
(size, offsetSize, offsetStart, dataStart) -> {
if (index < 0 || index >= size) {
return null;
}
int offset = readUnsigned(value, offsetStart + offsetSize * index, offsetSize);
return new BinaryVariant(value, metadata, dataStart + offset);
});
}
// Escape a string so that it can be pasted into JSON structure.
// For example, if `str` only contains a new-line character, then the result content is "\n"
// (4 characters).
private static String escapeJson(String str) {
try (CharArrayWriter writer = new CharArrayWriter();
JsonGenerator gen = new JsonFactory().createGenerator(writer)) {
gen.writeString(str);
gen.flush();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void appendQuoted(StringBuilder sb, String str) {
sb.append('"');
sb.append(str);
sb.append('"');
}
@Override
public String toString() {
return toJson();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BinaryVariant)) {
return false;
}
BinaryVariant variant = (BinaryVariant) o;
return getPos() == variant.getPos()
&& Objects.deepEquals(getValue(), variant.getValue())
&& Objects.deepEquals(getMetadata(), variant.getMetadata());
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(value), Arrays.hashCode(metadata), pos);
}
}
|
BinaryVariant
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/windowing/windows/TimeWindow.java
|
{
"start": 1765,
"end": 4160
}
|
class ____ extends Window {
private final long start;
private final long end;
public TimeWindow(long start, long end) {
this.start = start;
this.end = end;
}
/**
* Gets the starting timestamp of the window. This is the first timestamp that belongs to this
* window.
*
* @return The starting timestamp of this window.
*/
public long getStart() {
return start;
}
/**
* Gets the end timestamp of this window. The end timestamp is exclusive, meaning it is the
* first timestamp that does not belong to this window any more.
*
* @return The exclusive end timestamp of this window.
*/
public long getEnd() {
return end;
}
/**
* Gets the largest timestamp that still belongs to this window.
*
* <p>This timestamp is identical to {@code getEnd() - 1}.
*
* @return The largest timestamp that still belongs to this window.
* @see #getEnd()
*/
@Override
public long maxTimestamp() {
return end - 1;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimeWindow window = (TimeWindow) o;
return end == window.end && start == window.start;
}
@Override
public int hashCode() {
return MathUtils.longToIntWithBitMixing(start + end);
}
@Override
public String toString() {
return "TimeWindow{" + "start=" + start + ", end=" + end + '}';
}
/**
* Returns {@code true} if this window intersects the given window or if this window is just
* after or before the given window.
*/
public boolean intersects(TimeWindow other) {
return this.start <= other.end && this.end >= other.start;
}
/** Returns the minimal window covers both this window and the given window. */
public TimeWindow cover(TimeWindow other) {
return new TimeWindow(Math.min(start, other.start), Math.max(end, other.end));
}
// ------------------------------------------------------------------------
// Serializer
// ------------------------------------------------------------------------
/** The serializer used to write the TimeWindow type. */
public static
|
TimeWindow
|
java
|
spring-projects__spring-framework
|
spring-context/src/testFixtures/java/org/springframework/context/testfixture/index/CandidateComponentsTestClassLoader.java
|
{
"start": 1181,
"end": 3328
}
|
class ____ extends ClassLoader {
/**
* Create a test {@link ClassLoader} that disables the use of the index, even
* if resources are present at the standard location.
* @param classLoader the classloader to use for all other operations
* @return a test {@link ClassLoader} that has no index
* @see org.springframework.context.index.CandidateComponentsIndexLoader#COMPONENTS_RESOURCE_LOCATION
*/
public static ClassLoader disableIndex(ClassLoader classLoader) {
return new CandidateComponentsTestClassLoader(classLoader, Collections.emptyEnumeration());
}
/**
* Create a test {@link ClassLoader} that creates an index with the
* specified {@link Resource} instances.
* @param classLoader the classloader to use for all other operations
* @param resources the resources for index files
* @return a test {@link ClassLoader} with an index built based on the
* specified resources.
*/
public static ClassLoader index(ClassLoader classLoader, Resource... resources) {
return new CandidateComponentsTestClassLoader(classLoader,
Collections.enumeration(Stream.of(resources).map(r -> {
try {
return r.getURL();
}
catch (Exception ex) {
throw new IllegalArgumentException("Invalid resource " + r, ex);
}
}).toList()));
}
private final @Nullable Enumeration<URL> resourceUrls;
private final @Nullable IOException cause;
public CandidateComponentsTestClassLoader(ClassLoader classLoader, Enumeration<URL> resourceUrls) {
super(classLoader);
this.resourceUrls = resourceUrls;
this.cause = null;
}
public CandidateComponentsTestClassLoader(ClassLoader parent, IOException cause) {
super(parent);
this.resourceUrls = null;
this.cause = cause;
}
@Override
@SuppressWarnings({ "deprecation", "removal" })
public Enumeration<URL> getResources(String name) throws IOException {
if (org.springframework.context.index.CandidateComponentsIndexLoader.COMPONENTS_RESOURCE_LOCATION.equals(name)) {
if (this.resourceUrls != null) {
return this.resourceUrls;
}
throw this.cause;
}
return super.getResources(name);
}
}
|
CandidateComponentsTestClassLoader
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/testng/transaction/ejb/AbstractEjbTxDaoTestNGTests.java
|
{
"start": 1510,
"end": 2740
}
|
class ____ extends AbstractTransactionalTestNGSpringContextTests {
protected static final String TEST_NAME = "test-name";
@EJB
protected TestEntityDao dao;
@Autowired
protected EntityManager em;
@Test
void test1InitialState() {
int count = dao.getCount(TEST_NAME);
assertThat(count).as("New TestEntity should have count=0.").isEqualTo(0);
}
@Test(dependsOnMethods = "test1InitialState")
void test2IncrementCount1() {
int count = dao.incrementCount(TEST_NAME);
assertThat(count).as("Expected count=1 after first increment.").isEqualTo(1);
}
/**
* The default implementation of this method assumes that the transaction
* for {@link #test2IncrementCount1()} was committed. Therefore, it is
* expected that the previous increment has been persisted in the database.
*/
@Test(dependsOnMethods = "test2IncrementCount1")
void test3IncrementCount2() {
int count = dao.getCount(TEST_NAME);
assertThat(count).as("Expected count=1 after test2IncrementCount1().").isEqualTo(1);
count = dao.incrementCount(TEST_NAME);
assertThat(count).as("Expected count=2 now.").isEqualTo(2);
}
@AfterMethod(alwaysRun = true)
void synchronizePersistenceContext() {
em.flush();
}
}
|
AbstractEjbTxDaoTestNGTests
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/SealedTypesWithExistingPropertyTest.java
|
{
"start": 839,
"end": 1059
}
|
class ____ permits Apple, Orange {
public String name;
protected Fruit(String n) { name = n; }
}
@JsonTypeName("apple")
@JsonPropertyOrder({ "name", "seedCount", "type" })
static final
|
Fruit
|
java
|
processing__processing4
|
core/src/processing/data/DoubleDict.java
|
{
"start": 4166,
"end": 18763
}
|
class ____ {
public String key;
public double value;
Entry(String key, double value) {
this.key = key;
this.value = value;
}
}
public Iterable<Entry> entries() {
return new Iterable<Entry>() {
public Iterator<Entry> iterator() {
return entryIterator();
}
};
}
public Iterator<Entry> entryIterator() {
return new Iterator<Entry>() {
int index = -1;
public void remove() {
removeIndex(index);
index--;
}
public Entry next() {
++index;
Entry e = new Entry(keys[index], values[index]);
return e;
}
public boolean hasNext() {
return index+1 < size();
}
};
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public String key(int index) {
return keys[index];
}
protected void crop() {
if (count != keys.length) {
keys = PApplet.subset(keys, 0, count);
values = PApplet.subset(values, 0, count);
}
}
public Iterable<String> keys() {
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return keyIterator();
}
};
}
// Use this to iterate when you want to be able to remove elements along the way
public Iterator<String> keyIterator() {
return new Iterator<String>() {
int index = -1;
public void remove() {
removeIndex(index);
index--;
}
public String next() {
return key(++index);
}
public boolean hasNext() {
return index+1 < size();
}
};
}
/**
* Return a copy of the internal keys array. This array can be modified.
*
* @webref doubledict:method
* @brief Return a copy of the internal keys array
*/
public String[] keyArray() {
crop();
return keyArray(null);
}
public String[] keyArray(String[] outgoing) {
if (outgoing == null || outgoing.length != count) {
outgoing = new String[count];
}
System.arraycopy(keys, 0, outgoing, 0, count);
return outgoing;
}
public double value(int index) {
return values[index];
}
/**
* @webref doubledict:method
* @brief Return the internal array being used to store the values
*/
public Iterable<Double> values() {
return new Iterable<Double>() {
@Override
public Iterator<Double> iterator() {
return valueIterator();
}
};
}
public Iterator<Double> valueIterator() {
return new Iterator<Double>() {
int index = -1;
public void remove() {
removeIndex(index);
index--;
}
public Double next() {
return value(++index);
}
public boolean hasNext() {
return index+1 < size();
}
};
}
/**
* Create a new array and copy each of the values into it.
*
* @webref doubledict:method
* @brief Create a new array and copy each of the values into it
*/
public double[] valueArray() {
crop();
return valueArray(null);
}
/**
* Fill an already-allocated array with the values (more efficient than
* creating a new array each time). If 'array' is null, or not the same
* size as the number of values, a new array will be allocated and returned.
*/
public double[] valueArray(double[] array) {
if (array == null || array.length != size()) {
array = new double[count];
}
System.arraycopy(values, 0, array, 0, count);
return array;
}
/**
* Return a value for the specified key.
*
* @webref doubledict:method
* @brief Return a value for the specified key
*/
public double get(String key) {
int index = index(key);
if (index == -1) {
throw new IllegalArgumentException("No key named '" + key + "'");
}
return values[index];
}
public double get(String key, double alternate) {
int index = index(key);
if (index == -1) {
return alternate;
}
return values[index];
}
/**
* @webref doubledict:method
* @brief Create a new key/value pair or change the value of one
*/
public void set(String key, double amount) {
int index = index(key);
if (index == -1) {
create(key, amount);
} else {
values[index] = amount;
}
}
public void setIndex(int index, String key, double value) {
if (index < 0 || index >= count) {
throw new ArrayIndexOutOfBoundsException(index);
}
keys[index] = key;
values[index] = value;
}
/**
* @webref doubledict:method
* @brief Check if a key is a part of the data structure
*/
public boolean hasKey(String key) {
return index(key) != -1;
}
/**
* @webref doubledict:method
* @brief Add to a value
*/
public void add(String key, double amount) {
int index = index(key);
if (index == -1) {
create(key, amount);
} else {
values[index] += amount;
}
}
/**
* @webref doubledict:method
* @brief Subtract from a value
*/
public void sub(String key, double amount) {
add(key, -amount);
}
/**
* @webref doubledict:method
* @brief Multiply a value
*/
public void mult(String key, double amount) {
int index = index(key);
if (index != -1) {
values[index] *= amount;
}
}
/**
* @webref doubledict:method
* @brief Divide a value
*/
public void div(String key, double amount) {
int index = index(key);
if (index != -1) {
values[index] /= amount;
}
}
private void checkMinMax(String functionName) {
if (count == 0) {
String msg =
String.format("Cannot use %s() on an empty %s.",
functionName, getClass().getSimpleName());
throw new RuntimeException(msg);
}
}
/**
* @webref doublelist:method
* @brief Return the smallest value
*/
public int minIndex() {
//checkMinMax("minIndex");
if (count == 0) return -1;
// Will still return NaN if there are 1 or more entries, and they're all NaN
double m = Float.NaN;
int mi = -1;
for (int i = 0; i < count; i++) {
// find one good value to start
if (values[i] == values[i]) {
m = values[i];
mi = i;
// calculate the rest
for (int j = i+1; j < count; j++) {
double d = values[j];
if ((d == d) && (d < m)) {
m = values[j];
mi = j;
}
}
break;
}
}
return mi;
}
// return the key for the minimum value
public String minKey() {
checkMinMax("minKey");
int index = minIndex();
if (index == -1) {
return null;
}
return keys[index];
}
// return the minimum value, or throw an error if there are no values
public double minValue() {
checkMinMax("minValue");
int index = minIndex();
if (index == -1) {
return Float.NaN;
}
return values[index];
}
/**
* @webref doublelist:method
* @brief Return the largest value
*/
// The index of the entry that has the max value. Reference above is incorrect.
public int maxIndex() {
//checkMinMax("maxIndex");
if (count == 0) {
return -1;
}
// Will still return NaN if there is 1 or more entries, and they're all NaN
double m = Double.NaN;
int mi = -1;
for (int i = 0; i < count; i++) {
// find one good value to start
if (values[i] == values[i]) {
m = values[i];
mi = i;
// calculate the rest
for (int j = i+1; j < count; j++) {
double d = values[j];
if (!Double.isNaN(d) && (d > m)) {
m = values[j];
mi = j;
}
}
break;
}
}
return mi;
}
/** The key for a max value; null if empty or everything is NaN (no max). */
public String maxKey() {
//checkMinMax("maxKey");
int index = maxIndex();
if (index == -1) {
return null;
}
return keys[index];
}
/** The max value. (Or NaN if no entries or they're all NaN.) */
public double maxValue() {
//checkMinMax("maxValue");
int index = maxIndex();
if (index == -1) {
return Float.NaN;
}
return values[index];
}
public double sum() {
double sum = 0;
for (int i = 0; i < count; i++) {
sum += values[i];
}
return sum;
}
public int index(String what) {
Integer found = indices.get(what);
return (found == null) ? -1 : found.intValue();
}
protected void create(String what, double much) {
if (count == keys.length) {
keys = PApplet.expand(keys);
values = PApplet.expand(values);
}
indices.put(what, Integer.valueOf(count));
keys[count] = what;
values[count] = much;
count++;
}
/**
* @webref doubledict:method
* @brief Remove a key/value pair
*/
public double remove(String key) {
int index = index(key);
if (index == -1) {
throw new NoSuchElementException("'" + key + "' not found");
}
double value = values[index];
removeIndex(index);
return value;
}
public double removeIndex(int index) {
if (index < 0 || index >= count) {
throw new ArrayIndexOutOfBoundsException(index);
}
double value = values[index];
indices.remove(keys[index]);
for (int i = index; i < count-1; i++) {
keys[i] = keys[i+1];
values[i] = values[i+1];
indices.put(keys[i], i);
}
count--;
keys[count] = null;
values[count] = 0;
return value;
}
public void swap(int a, int b) {
String tkey = keys[a];
double tvalue = values[a];
keys[a] = keys[b];
values[a] = values[b];
keys[b] = tkey;
values[b] = tvalue;
// indices.put(keys[a], Integer.valueOf(a));
// indices.put(keys[b], Integer.valueOf(b));
}
/**
* Sort the keys alphabetically (ignoring case). Uses the value as a
* tie-breaker (only really possible with a key that has a case change).
*
* @webref doubledict:method
* @brief Sort the keys alphabetically
*/
public void sortKeys() {
sortImpl(true, false, true);
}
/**
* @webref doubledict:method
* @brief Sort the keys alphabetically in reverse
*/
public void sortKeysReverse() {
sortImpl(true, true, true);
}
/**
* Sort by values in descending order (largest value will be at [0]).
*
* @webref doubledict:method
* @brief Sort by values in ascending order
*/
public void sortValues() {
sortValues(true);
}
/**
* Set true to ensure that the order returned is identical. Slightly
* slower because the tie-breaker for identical values compares the keys.
* @param stable
*/
public void sortValues(boolean stable) {
sortImpl(false, false, stable);
}
/**
* @webref doubledict:method
* @brief Sort by values in descending order
*/
public void sortValuesReverse() {
sortValuesReverse(true);
}
public void sortValuesReverse(boolean stable) {
sortImpl(false, true, stable);
}
protected void sortImpl(final boolean useKeys, final boolean reverse,
final boolean stable) {
Sort s = new Sort() {
@Override
public int size() {
if (useKeys) {
return count; // don't worry about NaN values
} else if (count == 0) { // skip the NaN check, it'll AIOOBE
return 0;
} else { // first move NaN values to the end of the list
int right = count - 1;
while (values[right] != values[right]) {
right--;
if (right == -1) {
return 0; // all values are NaN
}
}
for (int i = right; i >= 0; --i) {
if (Double.isNaN(values[i])) {
swap(i, right);
--right;
}
}
return right + 1;
}
}
@Override
public int compare(int a, int b) {
double diff = 0;
if (useKeys) {
diff = keys[a].compareToIgnoreCase(keys[b]);
if (diff == 0) {
diff = values[a] - values[b];
}
} else { // sort values
diff = values[a] - values[b];
if (diff == 0 && stable) {
diff = keys[a].compareToIgnoreCase(keys[b]);
}
}
if (diff == 0) {
return 0;
} else if (reverse) {
return diff < 0 ? 1 : -1;
} else {
return diff < 0 ? -1 : 1;
}
}
@Override
public void swap(int a, int b) {
DoubleDict.this.swap(a, b);
}
};
s.run();
// Set the indices after sort/swaps (performance fix 160411)
resetIndices();
}
/**
* Sum all of the values in this dictionary, then return a new FloatDict of
* each key, divided by the total sum. The total for all values will be ~1.0.
* @return a FloatDict with the original keys, mapped to their pct of the total
*/
public DoubleDict getPercent() {
double sum = sum();
DoubleDict outgoing = new DoubleDict();
for (int i = 0; i < size(); i++) {
double percent = value(i) / sum;
outgoing.set(key(i), percent);
}
return outgoing;
}
/** Returns a duplicate copy of this object. */
public DoubleDict copy() {
DoubleDict outgoing = new DoubleDict(count);
System.arraycopy(keys, 0, outgoing.keys, 0, count);
System.arraycopy(values, 0, outgoing.values, 0, count);
for (int i = 0; i < count; i++) {
outgoing.indices.put(keys[i], i);
}
outgoing.count = count;
return outgoing;
}
public void print() {
for (int i = 0; i < size(); i++) {
System.out.println(keys[i] + " = " + values[i]);
}
}
/**
* Save tab-delimited entries to a file (TSV format, UTF-8 encoding)
*/
public void save(File file) {
PrintWriter writer = PApplet.createWriter(file);
write(writer);
writer.close();
}
/**
* Write tab-delimited entries out to
* @param writer
*/
public void write(PrintWriter writer) {
for (int i = 0; i < count; i++) {
writer.println(keys[i] + "\t" + values[i]);
}
writer.flush();
}
/**
* Return this dictionary as a String in JSON format.
*/
public String toJSON() {
StringList items = new StringList();
for (int i = 0; i < count; i++) {
items.append(JSONObject.quote(keys[i])+ ": " + values[i]);
}
return "{ " + items.join(", ") + " }";
}
@Override
public String toString() {
return getClass().getSimpleName() + " size=" + size() + " " + toJSON();
}
}
|
Entry
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/id/hhh12973/SequenceMismatchStrategyLogTest.java
|
{
"start": 1685,
"end": 3522
}
|
class ____ extends EntityManagerFactoryBasedFunctionalTest {
@RegisterExtension
public LoggerInspectionExtension logInspection =
LoggerInspectionExtension.builder().setLogger( SEQUENCE_GENERATOR_LOGGER ).build();
private final Triggerable triggerable = logInspection.watchForLogMessages( "HHH090202:" );
protected ServiceRegistry serviceRegistry;
protected MetadataImplementor metadata;
@Override
public EntityManagerFactory produceEntityManagerFactory() {
serviceRegistry = ServiceRegistryUtil.serviceRegistry();
metadata = (MetadataImplementor) new MetadataSources( serviceRegistry )
.addAnnotatedClass( ApplicationConfigurationHBM2DDL.class )
.buildMetadata();
new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), metadata );
return super.produceEntityManagerFactory();
}
@AfterAll
public void releaseResources() {
if ( metadata != null ) {
new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata );
}
if ( serviceRegistry != null ) {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
ApplicationConfiguration.class,
};
}
@Override
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.HBM2DDL_AUTO, "none" );
options.put( AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY, "log" );
triggerable.reset();
assertFalse( triggerable.wasTriggered() );
}
@Override
protected void entityManagerFactoryBuilt(EntityManagerFactory factory) {
assertTrue( triggerable.wasTriggered() );
}
@Override
protected boolean exportSchema() {
return false;
}
@Test
public void test() {
produceEntityManagerFactory();
}
@Entity
@Table(name = "application_configurations")
public static
|
SequenceMismatchStrategyLogTest
|
java
|
apache__dubbo
|
dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java
|
{
"start": 895,
"end": 1147
}
|
class ____ extends AppResponse implements com.alibaba.dubbo.rpc.Result {
public RpcResult() {}
public RpcResult(Object result) {
super(result);
}
public RpcResult(Throwable exception) {
super(exception);
}
}
|
RpcResult
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/rest/action/cat/RestThreadPoolAction.java
|
{
"start": 2493,
"end": 12395
}
|
class ____ extends AbstractCatAction {
private static final Set<String> RESPONSE_PARAMS = addToCopy(AbstractCatAction.RESPONSE_PARAMS, "thread_pool_patterns");
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_cat/thread_pool"), new Route(GET, "/_cat/thread_pool/{thread_pool_patterns}"));
}
@Override
public String getName() {
return "cat_threadpool_action";
}
@Override
protected void documentation(StringBuilder sb) {
sb.append("/_cat/thread_pool\n");
sb.append("/_cat/thread_pool/{thread_pools}\n");
}
@Override
public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(getMasterNodeTimeout(request));
clusterStateRequest.clear().nodes(true);
RestUtils.consumeDeprecatedLocalParameter(request);
return channel -> client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void processResponse(final ClusterStateResponse clusterStateResponse) {
NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
nodesInfoRequest.clear()
.addMetrics(NodesInfoMetrics.Metric.PROCESS.metricName(), NodesInfoMetrics.Metric.THREAD_POOL.metricName());
client.admin().cluster().nodesInfo(nodesInfoRequest, new RestActionListener<NodesInfoResponse>(channel) {
@Override
public void processResponse(final NodesInfoResponse nodesInfoResponse) {
NodesStatsRequest nodesStatsRequest = new NodesStatsRequest();
nodesStatsRequest.setIncludeShardsStats(false);
nodesStatsRequest.clear().addMetric(NodesStatsRequestParameters.Metric.THREAD_POOL);
client.admin().cluster().nodesStats(nodesStatsRequest, new RestResponseListener<NodesStatsResponse>(channel) {
@Override
public RestResponse buildResponse(NodesStatsResponse nodesStatsResponse) throws Exception {
return RestTable.buildResponse(
buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse),
channel
);
}
});
}
});
}
});
}
@Override
protected Set<String> responseParams() {
return RESPONSE_PARAMS;
}
@Override
protected Table getTableWithHeader(final RestRequest request) {
final Table table = new Table();
table.startHeaders();
table.addCell("node_name", "default:true;alias:nn;desc:node name");
table.addCell("node_id", "default:false;alias:id;desc:persistent node id");
table.addCell("ephemeral_node_id", "default:false;alias:eid;desc:ephemeral node id");
table.addCell("pid", "default:false;alias:p;desc:process id");
table.addCell("host", "default:false;alias:h;desc:host name");
table.addCell("ip", "default:false;alias:i;desc:ip address");
table.addCell("port", "default:false;alias:po;desc:bound transport port");
table.addCell("name", "default:true;alias:n;desc:thread pool name");
table.addCell("type", "alias:t;default:false;desc:thread pool type");
table.addCell("active", "alias:a;default:true;text-align:right;desc:number of active threads");
table.addCell("pool_size", "alias:psz;default:false;text-align:right;desc:number of threads");
table.addCell("queue", "alias:q;default:true;text-align:right;desc:number of tasks currently in queue");
table.addCell("queue_size", "alias:qs;default:false;text-align:right;desc:maximum number of tasks permitted in queue");
table.addCell("rejected", "alias:r;default:true;text-align:right;desc:number of rejected tasks");
table.addCell("largest", "alias:l;default:false;text-align:right;desc:highest number of seen active threads");
table.addCell("completed", "alias:c;default:false;text-align:right;desc:number of completed tasks");
table.addCell("core", "alias:cr;default:false;text-align:right;desc:core number of threads in a scaling thread pool");
table.addCell("max", "alias:mx;default:false;text-align:right;desc:maximum number of threads in a scaling thread pool");
table.addCell("size", "alias:sz;default:false;text-align:right;desc:number of threads in a fixed thread pool");
table.addCell("keep_alive", "alias:ka;default:false;text-align:right;desc:thread keep alive time");
table.endHeaders();
return table;
}
private Table buildTable(RestRequest req, ClusterStateResponse state, NodesInfoResponse nodesInfo, NodesStatsResponse nodesStats) {
final String[] threadPools = req.paramAsStringArray("thread_pool_patterns", new String[] { "*" });
final DiscoveryNodes nodes = state.getState().nodes();
final Table table = getTableWithHeader(req);
// collect all thread pool names that we see across the nodes
final Set<String> candidates = new HashSet<>();
for (final NodeStats nodeStats : nodesStats.getNodes()) {
for (final ThreadPoolStats.Stats threadPoolStats : nodeStats.getThreadPool()) {
candidates.add(threadPoolStats.name());
}
}
// collect all thread pool names that match the specified thread pool patterns
final Set<String> included = new HashSet<>();
for (final String candidate : candidates) {
if (Regex.simpleMatch(threadPools, candidate)) {
included.add(candidate);
}
}
for (final DiscoveryNode node : nodes) {
final NodeInfo info = nodesInfo.getNodesMap().get(node.getId());
final NodeStats stats = nodesStats.getNodesMap().get(node.getId());
final Map<String, ThreadPoolStats.Stats> poolThreadStats;
final Map<String, ThreadPool.Info> poolThreadInfo;
if (stats == null) {
poolThreadStats = Collections.emptyMap();
poolThreadInfo = Collections.emptyMap();
} else {
// we use a sorted map to ensure that thread pools are sorted by name
poolThreadStats = new TreeMap<>();
poolThreadInfo = new HashMap<>();
ThreadPoolStats threadPoolStats = stats.getThreadPool();
for (ThreadPoolStats.Stats threadPoolStat : threadPoolStats) {
poolThreadStats.put(threadPoolStat.name(), threadPoolStat);
}
if (info != null) {
for (ThreadPool.Info threadPoolInfo : info.getInfo(ThreadPoolInfo.class)) {
poolThreadInfo.put(threadPoolInfo.getName(), threadPoolInfo);
}
}
}
for (Map.Entry<String, ThreadPoolStats.Stats> entry : poolThreadStats.entrySet()) {
if (included.contains(entry.getKey()) == false) {
continue;
}
table.startRow();
table.addCell(node.getName());
table.addCell(node.getId());
table.addCell(node.getEphemeralId());
table.addCell(info == null ? null : info.getInfo(ProcessInfo.class).getId());
table.addCell(node.getHostName());
table.addCell(node.getHostAddress());
table.addCell(node.getAddress().address().getPort());
final ThreadPoolStats.Stats poolStats = entry.getValue();
final ThreadPool.Info poolInfo = poolThreadInfo.get(entry.getKey());
Long maxQueueSize = null;
TimeValue keepAlive = null;
Integer core = null;
Integer max = null;
Integer size = null;
if (poolInfo != null) {
maxQueueSize = poolInfo.getQueueSize();
if (poolInfo.getKeepAlive() != null) {
keepAlive = poolInfo.getKeepAlive();
}
if (poolInfo.getThreadPoolType() == ThreadPool.ThreadPoolType.SCALING) {
assert poolInfo.getMin() >= 0;
core = poolInfo.getMin();
assert poolInfo.getMax() > 0;
max = poolInfo.getMax();
} else {
assert poolInfo.getMin() == poolInfo.getMax() && poolInfo.getMax() > 0;
size = poolInfo.getMax();
}
}
table.addCell(entry.getKey());
table.addCell(poolInfo == null ? null : poolInfo.getThreadPoolType().getType());
table.addCell(poolStats == null ? null : poolStats.active());
table.addCell(poolStats == null ? null : poolStats.threads());
table.addCell(poolStats == null ? null : poolStats.queue());
table.addCell(maxQueueSize == null ? -1 : maxQueueSize);
table.addCell(poolStats == null ? null : poolStats.rejected());
table.addCell(poolStats == null ? null : poolStats.largest());
table.addCell(poolStats == null ? null : poolStats.completed());
table.addCell(core);
table.addCell(max);
table.addCell(size);
table.addCell(keepAlive);
table.endRow();
}
}
return table;
}
}
|
RestThreadPoolAction
|
java
|
quarkusio__quarkus
|
extensions/redis-cache/deployment/src/test/java/io/quarkus/cache/redis/deployment/SimpleCachedService.java
|
{
"start": 271,
"end": 673
}
|
class ____ {
static final String CACHE_NAME = "test-cache";
@CacheResult(cacheName = CACHE_NAME)
public String cachedMethod(String key) {
return UUID.randomUUID().toString();
}
@CacheInvalidate(cacheName = CACHE_NAME)
public void invalidate(String key) {
}
@CacheInvalidateAll(cacheName = CACHE_NAME)
public void invalidateAll() {
}
}
|
SimpleCachedService
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/locale/LocaleResolversWrapper.java
|
{
"start": 552,
"end": 1056
}
|
class ____ implements LocaleResolver {
@Inject
Instance<LocaleResolver> resolvers;
@Override
public Locale resolve(LocaleResolverContext context) {
for (LocaleResolver resolver : resolvers) {
if (!resolver.equals(this)) {
Locale locale = resolver.resolve(context);
if (locale != null) {
return locale;
}
}
}
return context.getDefaultLocale();
}
}
|
LocaleResolversWrapper
|
java
|
spring-projects__spring-boot
|
module/spring-boot-restclient/src/test/java/org/springframework/boot/restclient/autoconfigure/observation/RestClientObservationAutoConfigurationWithoutMetricsTests.java
|
{
"start": 2284,
"end": 3441
}
|
class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(ObservationRegistry.class, TestObservationRegistry::create)
.withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, RestClientAutoConfiguration.class,
RestClientObservationAutoConfiguration.class));
@Test
void restClientCreatedWithBuilderIsInstrumented() {
this.contextRunner.run((context) -> {
RestClient restClient = buildRestClient(context);
restClient.get().uri("/projects/{project}", "spring-boot").retrieve().toBodilessEntity();
TestObservationRegistry registry = context.getBean(TestObservationRegistry.class);
assertThat(registry).hasObservationWithNameEqualToIgnoringCase("http.client.requests");
});
}
private RestClient buildRestClient(AssertableApplicationContext context) {
Builder builder = context.getBean(Builder.class);
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("/projects/spring-boot")).andRespond(withStatus(HttpStatus.OK));
return builder.build();
}
}
|
RestClientObservationAutoConfigurationWithoutMetricsTests
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/SaveFederationQueuePolicyResponse.java
|
{
"start": 1149,
"end": 1715
}
|
class ____ {
public static SaveFederationQueuePolicyResponse newInstance() {
return Records.newRecord(SaveFederationQueuePolicyResponse.class);
}
public static SaveFederationQueuePolicyResponse newInstance(String msg) {
SaveFederationQueuePolicyResponse response =
Records.newRecord(SaveFederationQueuePolicyResponse.class);
response.setMessage(msg);
return response;
}
@Public
@Unstable
public abstract String getMessage();
@Public
@Unstable
public abstract void setMessage(String msg);
}
|
SaveFederationQueuePolicyResponse
|
java
|
spring-projects__spring-boot
|
integration-test/spring-boot-test-integration-tests/src/test/java/org/springframework/boot/web/server/test/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java
|
{
"start": 1622,
"end": 1987
}
|
class ____
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
@Test
void restTemplateIsUserDefined() {
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
}
@Configuration(proxyBeanMethods = false)
@EnableWebFlux
@RestController
static
|
SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/ParameterizedTypeFixtures.java
|
{
"start": 1263,
"end": 2690
}
|
class ____<T> {
public final T value;
public MyParameterizedType(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public String getExpectedJson() {
String valueAsJson = getExpectedJson(value);
return String.format("{\"value\":%s}", valueAsJson);
}
private static String getExpectedJson(Object obj) {
Class<?> clazz = obj.getClass();
if (Primitives.isWrapperType(Primitives.wrap(clazz))) {
return obj.toString();
} else if (obj.getClass().equals(String.class)) {
return "\"" + obj.toString() + "\"";
} else {
// Try invoking a getExpectedJson() method if it exists
try {
Method method = clazz.getMethod("getExpectedJson");
Object results = method.invoke(obj);
return (String) results;
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
@Override
public int hashCode() {
return value == null ? 0 : value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MyParameterizedType<?>)) {
return false;
}
MyParameterizedType<?> that = (MyParameterizedType<?>) obj;
return Objects.equals(getValue(), that.getValue());
}
}
public static
|
MyParameterizedType
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java
|
{
"start": 17764,
"end": 17860
}
|
class ____ {
@Bean
public void testBean() {
}
}
@Configuration
static
|
ConfigWithVoidBean
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/benchmark/decode/Map1Decode.java
|
{
"start": 153,
"end": 606
}
|
class ____ extends BenchmarkCase {
private String text;
public Map1Decode(){
super("StringArray1000Decode");
this.text = "{\"badboy\":true,\"description\":\"神棍敌人姐\",\"name\":\"校长\",\"age\":3,\"birthdate\":1293278091773,\"salary\":123456789.0123}";
}
@Override
public void execute(Codec codec) throws Exception {
for (int i = 0; i < 10; ++i) {
codec.decodeObject(text);
}
}
}
|
Map1Decode
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/cfg/DatatypeFeatures.java
|
{
"start": 152,
"end": 246
}
|
class ____ contains settings for multiple
* {@link DatatypeFeature} enumerations.
*/
public
|
that
|
java
|
apache__camel
|
components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/spi/PlatformHttpConsumer.java
|
{
"start": 1023,
"end": 1210
}
|
interface ____ extends Consumer {
/**
* Gets the {@link PlatformHttpEndpoint} for the consumer.
*/
@Override
PlatformHttpEndpoint getEndpoint();
}
|
PlatformHttpConsumer
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalBinaryProcessor.java
|
{
"start": 571,
"end": 1839
}
|
class ____<T, U, R, F extends BiFunction<T, U, R>> extends BinaryProcessor {
private final F function;
protected FunctionalBinaryProcessor(Processor left, Processor right, F function) {
super(left, right);
this.function = function;
}
protected FunctionalBinaryProcessor(StreamInput in, Reader<F> reader) throws IOException {
super(in);
this.function = reader.read(in);
}
public F function() {
return function;
}
@SuppressWarnings("unchecked")
@Override
protected Object doProcess(Object left, Object right) {
return function.apply((T) left, (U) right);
}
@Override
public int hashCode() {
return Objects.hash(left(), right(), function());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
FunctionalBinaryProcessor<?, ?, ?, ?> other = (FunctionalBinaryProcessor<?, ?, ?, ?>) obj;
return Objects.equals(function(), other.function())
&& Objects.equals(left(), other.left())
&& Objects.equals(right(), other.right());
}
}
|
FunctionalBinaryProcessor
|
java
|
apache__dubbo
|
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java
|
{
"start": 1259,
"end": 1838
}
|
class ____ implements Processor {
@Override
public void process(Context context) throws DubboTestException {
ZookeeperWindowsContext zookeeperWindowsContext = (ZookeeperWindowsContext) context;
this.doProcess(zookeeperWindowsContext);
}
/**
* Use {@link Process} to handle the command.
*
* @param context the global zookeeper context.
* @throws DubboTestException when any exception occurred.
*/
protected abstract void doProcess(ZookeeperWindowsContext context) throws DubboTestException;
}
|
ZookeeperWindowsProcessor
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DaprEndpointBuilderFactory.java
|
{
"start": 39723,
"end": 44381
}
|
interface ____
extends
DaprEndpointConsumerBuilder,
DaprEndpointProducerBuilder {
default AdvancedDaprEndpointBuilder advanced() {
return (AdvancedDaprEndpointBuilder) this;
}
/**
* The Dapr Client.
*
* The option is a: <code>io.dapr.client.DaprClient</code> type.
*
* Group: common
*
* @param client the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder client(io.dapr.client.DaprClient client) {
doSetProperty("client", client);
return this;
}
/**
* The Dapr Client.
*
* The option will be converted to a
* <code>io.dapr.client.DaprClient</code> type.
*
* Group: common
*
* @param client the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder client(String client) {
doSetProperty("client", client);
return this;
}
/**
* List of keys for configuration operation.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param configKeys the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder configKeys(String configKeys) {
doSetProperty("configKeys", configKeys);
return this;
}
/**
* The name of the Dapr configuration store to interact with, defined in
* statestore.yaml config.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param configStore the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder configStore(String configStore) {
doSetProperty("configStore", configStore);
return this;
}
/**
* The contentType for the Pub/Sub component to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param contentType the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder contentType(String contentType) {
doSetProperty("contentType", contentType);
return this;
}
/**
* The Dapr Preview Client.
*
* The option is a: <code>io.dapr.client.DaprPreviewClient</code> type.
*
* Group: common
*
* @param previewClient the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder previewClient(io.dapr.client.DaprPreviewClient previewClient) {
doSetProperty("previewClient", previewClient);
return this;
}
/**
* The Dapr Preview Client.
*
* The option will be converted to a
* <code>io.dapr.client.DaprPreviewClient</code> type.
*
* Group: common
*
* @param previewClient the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder previewClient(String previewClient) {
doSetProperty("previewClient", previewClient);
return this;
}
/**
* The name of the Dapr Pub/Sub component to use. This identifies which
* underlying messaging system Dapr will interact with for publishing or
* subscribing to events.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param pubSubName the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder pubSubName(String pubSubName) {
doSetProperty("pubSubName", pubSubName);
return this;
}
/**
* The name of the topic to subscribe to. The topic must exist in the
* Pub/Sub component configured under the given pubsubName.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param topic the value to set
* @return the dsl builder
*/
default DaprEndpointBuilder topic(String topic) {
doSetProperty("topic", topic);
return this;
}
}
/**
* Advanced builder for endpoint for the Dapr component.
*/
public
|
DaprEndpointBuilder
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/streaming/api/operators/python/process/timer/TimerUtils.java
|
{
"start": 1222,
"end": 2011
}
|
class ____ {
public static TypeInformation<Row> createTimerDataTypeInfo(TypeInformation<Row> keyType) {
// structure: [timerType/timerOperationType, watermark, timestamp, key, namespace]
// 1) setTimer: [timerOperationType, null, timestamp, key, namespace]
// 2) onTimer: [timerType, watermark, timestamp, key, namespace]
return Types.ROW(
Types.BYTE, Types.LONG, Types.LONG, keyType, Types.PRIMITIVE_ARRAY(Types.BYTE));
}
public static FlinkFnApi.CoderInfoDescriptor createTimerDataCoderInfoDescriptorProto(
TypeInformation<Row> timerDataType) {
return ProtoUtils.createRawTypeCoderInfoDescriptorProto(
timerDataType, FlinkFnApi.CoderInfoDescriptor.Mode.SINGLE, false, null);
}
}
|
TimerUtils
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/ModUnsignedLongsEvaluator.java
|
{
"start": 1127,
"end": 5173
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ModUnsignedLongsEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator lhs;
private final EvalOperator.ExpressionEvaluator rhs;
private final DriverContext driverContext;
private Warnings warnings;
public ModUnsignedLongsEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs,
EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (LongBlock lhsBlock = (LongBlock) lhs.eval(page)) {
try (LongBlock rhsBlock = (LongBlock) rhs.eval(page)) {
LongVector lhsVector = lhsBlock.asVector();
if (lhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
LongVector rhsVector = rhsBlock.asVector();
if (rhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
return eval(page.getPositionCount(), lhsVector, rhsVector);
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += lhs.baseRamBytesUsed();
baseRamBytesUsed += rhs.baseRamBytesUsed();
return baseRamBytesUsed;
}
public LongBlock eval(int positionCount, LongBlock lhsBlock, LongBlock rhsBlock) {
try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (lhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (rhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
long lhs = lhsBlock.getLong(lhsBlock.getFirstValueIndex(p));
long rhs = rhsBlock.getLong(rhsBlock.getFirstValueIndex(p));
try {
result.appendLong(Mod.processUnsignedLongs(lhs, rhs));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
public LongBlock eval(int positionCount, LongVector lhsVector, LongVector rhsVector) {
try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
long lhs = lhsVector.getLong(p);
long rhs = rhsVector.getLong(p);
try {
result.appendLong(Mod.processUnsignedLongs(lhs, rhs));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
@Override
public String toString() {
return "ModUnsignedLongsEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(lhs, rhs);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
ModUnsignedLongsEvaluator
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/vertx/JsonArrayWriter.java
|
{
"start": 740,
"end": 1736
}
|
class ____ implements AsyncMessageBodyWriter<JsonArray> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type == JsonArray.class;
}
@Override
public void writeTo(JsonArray jsonArray, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(jsonArray.toBuffer().getBytes());
entityStream.flush();
entityStream.close();
}
@Override
public CompletionStage<Void> asyncWriteTo(JsonArray jsonArray, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
AsyncOutputStream entityStream) {
return entityStream.asyncWrite(jsonArray.toBuffer().getBytes());
}
}
|
JsonArrayWriter
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsonschema/NewSchemaTest.java
|
{
"start": 1056,
"end": 1234
}
|
enum ____ {
A, B, C;
@JsonValue
public String forSerialize() {
return "value-"+name();
}
}
// silly little
|
TestEnumWithJsonValue
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnalysis.java
|
{
"start": 2400,
"end": 4678
}
|
class ____ {
private final WellKnownMutability wellKnownMutability;
@Inject
Factory(WellKnownMutability wellKnownMutability) {
this.wellKnownMutability = wellKnownMutability;
}
public ImmutableAnalysis create(
BiPredicate<Symbol, VisitorState> suppressionChecker,
VisitorState state,
ImmutableSet<String> immutableAnnotations) {
return new ImmutableAnalysis(
suppressionChecker, state, wellKnownMutability, immutableAnnotations);
}
}
private final BiPredicate<Symbol, VisitorState> suppressionChecker;
private final VisitorState state;
private final WellKnownMutability wellKnownMutability;
private final ThreadSafety threadSafety;
private ImmutableAnalysis(
BiPredicate<Symbol, VisitorState> suppressionChecker,
VisitorState state,
WellKnownMutability wellKnownMutability,
ImmutableSet<String> immutableAnnotations) {
this.suppressionChecker = suppressionChecker;
this.state = state;
this.wellKnownMutability = wellKnownMutability;
this.threadSafety =
ThreadSafety.builder()
.purpose(Purpose.FOR_IMMUTABLE_CHECKER)
.markerAnnotationInherited(true)
.knownTypes(wellKnownMutability)
.markerAnnotations(immutableAnnotations)
.typeParameterAnnotation(ImmutableSet.of(ImmutableTypeParameter.class.getName()))
.build(state);
}
Violation isThreadSafeType(
boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) {
return threadSafety.isThreadSafeType(
allowContainerTypeParameters, containerTypeParameters, type);
}
boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol sym) {
return threadSafety.hasThreadSafeTypeParameterAnnotation(sym);
}
Violation checkInstantiation(
Collection<TypeVariableSymbol> classTypeParameters, Collection<Type> typeArguments) {
return threadSafety.checkInstantiation(classTypeParameters, typeArguments);
}
public Violation checkInvocation(Type methodType, Symbol symbol) {
return threadSafety.checkInvocation(methodType, symbol);
}
/** Accepts {@link Violation violations} that are found during the analysis. */
@FunctionalInterface
public
|
Factory
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/SplitTokenizerXmlMultilineTest.java
|
{
"start": 984,
"end": 1968
}
|
class ____ extends ContextTestSupport {
@Test
public void testSingleLine() throws Exception {
String payload = "<Parent>\n" + "\t<Child A=\"1\" B=\"2\"/>\n" + "</Parent>";
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", payload);
assertMockEndpointsSatisfied();
}
@Test
public void testMultipleLines() throws Exception {
String payload = "<Parent>\n" + "\t<Child A=\"1\"\n" + "\tB=\"2\"/>\n" + "</Parent>";
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", payload);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").split().tokenizeXML("Child").to("mock:result");
}
};
}
}
|
SplitTokenizerXmlMultilineTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/docker/compose/MySqlEnvironmentTests.java
|
{
"start": 1090,
"end": 3499
}
|
class ____ {
@Test
void createWhenHasMysqlRandomRootPasswordThrowsException() {
assertThatIllegalStateException()
.isThrownBy(() -> new MySqlEnvironment(Map.of("MYSQL_RANDOM_ROOT_PASSWORD", "true")))
.withMessage("MYSQL_RANDOM_ROOT_PASSWORD is not supported");
}
@Test
void createWhenHasNoPasswordThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> new MySqlEnvironment(Collections.emptyMap()))
.withMessage("No MySQL password found");
}
@Test
void createWhenHasNoDatabaseThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> new MySqlEnvironment(Map.of("MYSQL_PASSWORD", "secret")))
.withMessage("No MYSQL_DATABASE defined");
}
@Test
void getUsernameWhenHasMysqlUser() {
MySqlEnvironment environment = new MySqlEnvironment(
Map.of("MYSQL_USER", "myself", "MYSQL_PASSWORD", "secret", "MYSQL_DATABASE", "db"));
assertThat(environment.getUsername()).isEqualTo("myself");
}
@Test
void getUsernameWhenHasNoMysqlUser() {
MySqlEnvironment environment = new MySqlEnvironment(Map.of("MYSQL_PASSWORD", "secret", "MYSQL_DATABASE", "db"));
assertThat(environment.getUsername()).isEqualTo("root");
}
@Test
void getPasswordWhenHasMysqlPassword() {
MySqlEnvironment environment = new MySqlEnvironment(Map.of("MYSQL_PASSWORD", "secret", "MYSQL_DATABASE", "db"));
assertThat(environment.getPassword()).isEqualTo("secret");
}
@Test
void getPasswordWhenHasMysqlRootPassword() {
MySqlEnvironment environment = new MySqlEnvironment(
Map.of("MYSQL_ROOT_PASSWORD", "secret", "MYSQL_DATABASE", "db"));
assertThat(environment.getPassword()).isEqualTo("secret");
}
@Test
void getPasswordWhenHasNoPasswordAndMysqlAllowEmptyPassword() {
MySqlEnvironment environment = new MySqlEnvironment(
Map.of("MYSQL_ALLOW_EMPTY_PASSWORD", "true", "MYSQL_DATABASE", "db"));
assertThat(environment.getPassword()).isEmpty();
}
@Test
void getPasswordWhenHasNoPasswordAndAllowEmptyPassword() {
MySqlEnvironment environment = new MySqlEnvironment(
Map.of("ALLOW_EMPTY_PASSWORD", "true", "MYSQL_DATABASE", "db"));
assertThat(environment.getPassword()).isEmpty();
}
@Test
void getDatabaseWhenHasMysqlDatabase() {
MySqlEnvironment environment = new MySqlEnvironment(
Map.of("MYSQL_ALLOW_EMPTY_PASSWORD", "true", "MYSQL_DATABASE", "db"));
assertThat(environment.getDatabase()).isEqualTo("db");
}
}
|
MySqlEnvironmentTests
|
java
|
google__dagger
|
javatests/dagger/functional/builderbinds/BuilderSupertype.java
|
{
"start": 702,
"end": 804
}
|
interface ____ {
@BindsInstance
void boundInSubtype(@Named("subtype") int subtype);
}
|
BuilderSupertype
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/example/test/AutoClosableSoftAssertionsLineNumberTest.java
|
{
"start": 1171,
"end": 2565
}
|
class ____ {
@Test
void should_print_line_numbers_of_failed_assertions() {
AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions();
softly.assertThat(1)
.isLessThan(0)
.isLessThan(1);
// WHEN
var error = expectAssertionError(softly::close);
// THEN
assertThat(error).hasMessageContaining(format("%n"
+ "Expecting actual:%n"
+ " 1%n"
+ "to be less than:%n"
+ " 0 %n"
+ "at AutoClosableSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(AutoClosableSoftAssertionsLineNumberTest.java:36)%n"))
.hasMessageContaining(format("%n"
+ "Expecting actual:%n"
+ " 1%n"
+ "to be less than:%n"
+ " 1 %n"
+ "at AutoClosableSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(AutoClosableSoftAssertionsLineNumberTest.java:37)"));
}
}
|
AutoClosableSoftAssertionsLineNumberTest
|
java
|
apache__kafka
|
server/src/main/java/org/apache/kafka/server/AssignmentsManager.java
|
{
"start": 10080,
"end": 10997
}
|
class ____ implements EventQueue.Event {
private final Map<TopicIdPartition, Assignment> sent;
private final Optional<ClientResponse> response;
HandleResponseEvent(
Map<TopicIdPartition, Assignment> sent,
Optional<ClientResponse> response
) {
this.sent = sent;
this.response = response;
}
@Override
public void run() {
try {
handleResponse(sent, response);
} catch (Exception e) {
log.error("Unexpected exception in HandleResponseEvent", e);
} finally {
if (!ready.isEmpty()) {
rescheduleMaybeSendAssignmentsEvent(time.nanoseconds());
}
}
}
}
/**
* A callback object that handles the controller's response to our request.
*/
private
|
HandleResponseEvent
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentProcessorTest.java
|
{
"start": 55450,
"end": 55766
}
|
class ____ {",
" @Inject Foo() {}",
"}");
Source module =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
"import dagger.Module;",
"",
"@Module(subcomponents = Pruned.class)",
"
|
Foo
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/InferenceFeatures.java
|
{
"start": 2658,
"end": 7980
}
|
class ____ implements FeatureSpecification {
private static final NodeFeature SEMANTIC_TEXT_HIGHLIGHTER = new NodeFeature("semantic_text.highlighter");
private static final NodeFeature SEMANTIC_TEXT_HIGHLIGHTER_DEFAULT = new NodeFeature("semantic_text.highlighter.default");
private static final NodeFeature SEMANTIC_TEXT_HIGHLIGHTER_DISKBBQ_SIMILARITY_SUPPORT = new NodeFeature(
"semantic_text.highlighter.bbq_and_similarity_support"
);
private static final NodeFeature SEMANTIC_TEXT_HIGHLIGHTER_VECTOR_SIMILARITY_SUPPORT = new NodeFeature(
"semantic_text.highlighter.vector_similarity_support"
);
private static final NodeFeature TEST_RERANKING_SERVICE_PARSE_TEXT_AS_SCORE = new NodeFeature(
"test_reranking_service.parse_text_as_score"
);
private static final NodeFeature TEST_RULE_RETRIEVER_WITH_INDICES_THAT_DONT_RETURN_RANK_DOCS = new NodeFeature(
"test_rule_retriever.with_indices_that_dont_return_rank_docs"
);
private static final NodeFeature SEMANTIC_QUERY_REWRITE_INTERCEPTORS_PROPAGATE_BOOST_AND_QUERY_NAME_FIX = new NodeFeature(
"semantic_query_rewrite_interceptors.propagate_boost_and_query_name_fix"
);
private static final NodeFeature SEMANTIC_TEXT_MATCH_ALL_HIGHLIGHTER = new NodeFeature("semantic_text.match_all_highlighter");
private static final NodeFeature COHERE_V2_API = new NodeFeature("inference.cohere.v2");
public static final NodeFeature SEMANTIC_TEXT_HIGHLIGHTING_FLAT = new NodeFeature("semantic_text.highlighter.flat_index_options");
private static final NodeFeature SEMANTIC_TEXT_FIELDS_CHUNKS_FORMAT = new NodeFeature("semantic_text.fields_chunks_format");
public static final NodeFeature INFERENCE_ENDPOINT_CACHE = new NodeFeature("inference.endpoint.cache");
public static final NodeFeature INFERENCE_CCM_CACHE = new NodeFeature("inference.ccm.cache");
public static final NodeFeature SEARCH_USAGE_EXTENDED_DATA = new NodeFeature("search.usage.extended_data");
public static final NodeFeature INFERENCE_AUTH_POLLER_PERSISTENT_TASK = new NodeFeature("inference.auth_poller.persistent_task");
@Override
public Set<NodeFeature> getFeatures() {
return Set.of(INFERENCE_ENDPOINT_CACHE, INFERENCE_CCM_CACHE, INFERENCE_AUTH_POLLER_PERSISTENT_TASK);
}
@Override
public Set<NodeFeature> getTestFeatures() {
var testFeatures = new HashSet<>(
Set.of(
SemanticTextFieldMapper.SEMANTIC_TEXT_IN_OBJECT_FIELD_FIX,
SemanticTextFieldMapper.SEMANTIC_TEXT_SINGLE_FIELD_UPDATE_FIX,
SemanticTextFieldMapper.SEMANTIC_TEXT_DELETE_FIX,
SemanticTextFieldMapper.SEMANTIC_TEXT_ZERO_SIZE_FIX,
SemanticTextFieldMapper.SEMANTIC_TEXT_ALWAYS_EMIT_INFERENCE_ID_FIX,
SemanticTextFieldMapper.SEMANTIC_TEXT_SKIP_INFERENCE_FIELDS,
SEMANTIC_TEXT_HIGHLIGHTER,
SEMANTIC_MATCH_QUERY_REWRITE_INTERCEPTION_SUPPORTED,
SEMANTIC_SPARSE_VECTOR_QUERY_REWRITE_INTERCEPTION_SUPPORTED,
SemanticInferenceMetadataFieldsMapper.EXPLICIT_NULL_FIXES,
SEMANTIC_KNN_VECTOR_QUERY_REWRITE_INTERCEPTION_SUPPORTED,
TextSimilarityRankRetrieverBuilder.TEXT_SIMILARITY_RERANKER_ALIAS_HANDLING_FIX,
TextSimilarityRankRetrieverBuilder.TEXT_SIMILARITY_RERANKER_MINSCORE_FIX,
SemanticInferenceMetadataFieldsMapper.INFERENCE_METADATA_FIELDS_ENABLED_BY_DEFAULT,
SEMANTIC_TEXT_HIGHLIGHTER_DEFAULT,
SEMANTIC_KNN_FILTER_FIX,
TEST_RERANKING_SERVICE_PARSE_TEXT_AS_SCORE,
SemanticTextFieldMapper.SEMANTIC_TEXT_BIT_VECTOR_SUPPORT,
SemanticTextFieldMapper.SEMANTIC_TEXT_HANDLE_EMPTY_INPUT,
TEST_RULE_RETRIEVER_WITH_INDICES_THAT_DONT_RETURN_RANK_DOCS,
SEMANTIC_TEXT_SUPPORT_CHUNKING_CONFIG,
SEMANTIC_TEXT_MATCH_ALL_HIGHLIGHTER,
SEMANTIC_TEXT_EXCLUDE_SUB_FIELDS_FROM_FIELD_CAPS,
SEMANTIC_TEXT_INDEX_OPTIONS,
COHERE_V2_API,
SEMANTIC_TEXT_INDEX_OPTIONS_WITH_DEFAULTS,
SEMANTIC_QUERY_REWRITE_INTERCEPTORS_PROPAGATE_BOOST_AND_QUERY_NAME_FIX,
SEMANTIC_TEXT_HIGHLIGHTING_FLAT,
SEMANTIC_TEXT_SPARSE_VECTOR_INDEX_OPTIONS,
SEMANTIC_TEXT_FIELDS_CHUNKS_FORMAT,
SEMANTIC_TEXT_UPDATABLE_INFERENCE_ID,
SEMANTIC_TEXT_HIGHLIGHTER_DISKBBQ_SIMILARITY_SUPPORT,
SEMANTIC_TEXT_HIGHLIGHTER_VECTOR_SIMILARITY_SUPPORT,
SemanticQueryBuilder.SEMANTIC_QUERY_MULTIPLE_INFERENCE_IDS,
SemanticQueryBuilder.SEMANTIC_QUERY_FILTER_FIELD_CAPS_FIX,
InterceptedInferenceQueryBuilder.NEW_SEMANTIC_QUERY_INTERCEPTORS,
SemanticKnnVectorQueryRewriteInterceptor.SEMANTIC_KNN_VECTOR_QUERY_FILTERS_REWRITE_INTERCEPTION_SUPPORTED,
TEXT_SIMILARITY_RERANKER_SNIPPETS,
ModelStats.SEMANTIC_TEXT_USAGE,
SEARCH_USAGE_EXTENDED_DATA,
TEXT_SIMILARITY_RANK_DOC_EXPLAIN_CHUNKS
)
);
testFeatures.addAll(getFeatures());
return testFeatures;
}
}
|
InferenceFeatures
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java
|
{
"start": 2654,
"end": 3013
}
|
interface ____ {
@JSONField(name = "ID")
int getId();
@JSONField(name = "xid")
void setId(int value);
@JSONField(name = "NAME")
String getName(String xx);
@JSONField(name = "NAME")
String getName(String xx, int v);
@JSONField(name = "xid_1")
void setName(int value);
}
}
|
IV
|
java
|
apache__camel
|
core/camel-api/src/generated/java/org/apache/camel/spi/annotations/InfraService.java
|
{
"start": 1399,
"end": 2299
}
|
interface ____ used by Camel JBang infra run to retrieve testing information like port, endpoint, username...
*
* @return
*/
Class service();
/**
* Returns a description of this Service.
*
* This is used for documentation and tooling.
*
* @return
*/
String description() default "";
/**
* List of names that can be used to run the service
*
* @return
*/
String[] serviceAlias();
/**
* Additional and optional Service name, in case of multiple Service implementations
*
* For example kafka has 3 implementations
*
* kafka - uses apache/kafka image as implementation kafka redpanda - uses redpandadata/redpanda image as
* implementation kafka strimzi - uses strimzi/kafka as image implementation
*
* @return
*/
String[] serviceImplementationAlias() default {};
}
|
is
|
java
|
junit-team__junit5
|
documentation/src/test/java/example/DisplayNameGeneratorDemo.java
|
{
"start": 1964,
"end": 2327
}
|
class ____ {
@SentenceFragment("if it is divisible by 4 but not by 100")
@Test
void divisibleBy4ButNotBy100() {
}
@SentenceFragment("if it is one of the following years")
@ParameterizedTest(name = "{0}")
@ValueSource(ints = { 2016, 2020, 2048 })
void validLeapYear(int year) {
}
}
// end::user_guide_custom_sentence_fragments[]
}
|
LeapYearTests
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/extend/ExtendMapper.java
|
{
"start": 702,
"end": 778
}
|
interface ____ {
Parent selectParent();
Child selectChild();
}
|
ExtendMapper
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/StorageInfo.java
|
{
"start": 1827,
"end": 9612
}
|
class ____ {
public int layoutVersion; // layout version of the storage data
public int namespaceID; // id of the file system
public String clusterID; // id of the cluster
public long cTime; // creation time of the file system state
protected final NodeType storageType; // Type of the node using this storage
protected static final String STORAGE_FILE_VERSION = "VERSION";
public StorageInfo(NodeType type) {
this(0, 0, "", 0L, type);
}
public StorageInfo(int layoutV, int nsID, String cid, long cT, NodeType type) {
layoutVersion = layoutV;
clusterID = cid;
namespaceID = nsID;
cTime = cT;
storageType = type;
}
public StorageInfo(StorageInfo from) {
this(from.layoutVersion, from.namespaceID, from.clusterID, from.cTime,
from.storageType);
}
/**
* Layout version of the storage data.
*/
public int getLayoutVersion(){ return layoutVersion; }
/**
* Namespace id of the file system.<p>
* Assigned to the file system at formatting and never changes after that.
* Shared by all file system components.
*/
public int getNamespaceID() { return namespaceID; }
/**
* cluster id of the file system.<p>
*/
public String getClusterID() { return clusterID; }
/**
* Creation time of the file system state.<p>
* Modified during upgrades.
*/
public long getCTime() { return cTime; }
public void setStorageInfo(StorageInfo from) {
layoutVersion = from.layoutVersion;
clusterID = from.clusterID;
namespaceID = from.namespaceID;
cTime = from.cTime;
}
public boolean versionSupportsFederation(
Map<Integer, SortedSet<LayoutFeature>> map) {
return LayoutVersion.supports(map, LayoutVersion.Feature.FEDERATION,
layoutVersion);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("lv=").append(layoutVersion).append(";cid=").append(clusterID)
.append(";nsid=").append(namespaceID).append(";c=").append(cTime);
return sb.toString();
}
/**
* Returns string representation of Storage info attributes stored in Map.
*
* @return string representation of storage info attributes.
*/
public String toMapString() {
Map<String, Object> storageInfo = new HashMap<>();
storageInfo.put("LayoutVersion", layoutVersion);
storageInfo.put("ClusterId", clusterID);
storageInfo.put("NamespaceId", namespaceID);
storageInfo.put("CreationTime", cTime);
return storageInfo.toString();
}
public String toColonSeparatedString() {
return Joiner.on(":").join(
layoutVersion, namespaceID, cTime, clusterID);
}
public static int getNsIdFromColonSeparatedString(String in) {
return Integer.parseInt(in.split(":")[1]);
}
public static String getClusterIdFromColonSeparatedString(String in) {
return in.split(":")[3];
}
/**
* Read properties from the VERSION file in the given storage directory.
*/
public void readProperties(StorageDirectory sd) throws IOException {
Properties props = readPropertiesFile(sd.getVersionFile());
setFieldsFromProperties(props, sd);
}
/**
* Read properties from the the previous/VERSION file in the given storage directory.
*/
public void readPreviousVersionProperties(StorageDirectory sd)
throws IOException {
Properties props = readPropertiesFile(sd.getPreviousVersionFile());
setFieldsFromProperties(props, sd);
}
/**
* Get common storage fields.
* Should be overloaded if additional fields need to be get.
*
* @param props properties
* @throws IOException on error
*/
protected void setFieldsFromProperties(
Properties props, StorageDirectory sd) throws IOException {
if (props == null) {
return;
}
setLayoutVersion(props, sd);
setNamespaceID(props, sd);
setcTime(props, sd);
setClusterId(props, layoutVersion, sd);
checkStorageType(props, sd);
}
/** Validate and set storage type from {@link Properties}*/
protected void checkStorageType(Properties props, StorageDirectory sd)
throws InconsistentFSStateException {
if (storageType == null) { //don't care about storage type
return;
}
NodeType type = NodeType.valueOf(getProperty(props, sd, "storageType"));
if (!storageType.equals(type)) {
throw new InconsistentFSStateException(sd.root,
"Incompatible node types: storageType=" + storageType
+ " but StorageDirectory type=" + type);
}
}
/** Validate and set ctime from {@link Properties}*/
protected void setcTime(Properties props, StorageDirectory sd)
throws InconsistentFSStateException {
cTime = Long.parseLong(getProperty(props, sd, "cTime"));
}
/** Validate and set clusterId from {@link Properties}*/
protected void setClusterId(Properties props, int layoutVersion,
StorageDirectory sd) throws InconsistentFSStateException {
// Set cluster ID in version that supports federation
if (LayoutVersion.supports(getServiceLayoutFeatureMap(),
Feature.FEDERATION, layoutVersion)) {
String cid = getProperty(props, sd, "clusterID");
if (!(clusterID.equals("") || cid.equals("") || clusterID.equals(cid))) {
throw new InconsistentFSStateException(sd.getRoot(),
"cluster Id is incompatible with others.");
}
clusterID = cid;
}
}
/** Validate and set layout version from {@link Properties}*/
protected void setLayoutVersion(Properties props, StorageDirectory sd)
throws IncorrectVersionException, InconsistentFSStateException {
int lv = Integer.parseInt(getProperty(props, sd, "layoutVersion"));
if (lv < getServiceLayoutVersion()) { // future version
throw new IncorrectVersionException(getServiceLayoutVersion(), lv,
"storage directory " + sd.root.getAbsolutePath());
}
layoutVersion = lv;
}
/** Validate and set namespaceID version from {@link Properties}*/
protected void setNamespaceID(Properties props, StorageDirectory sd)
throws InconsistentFSStateException {
int nsId = Integer.parseInt(getProperty(props, sd, "namespaceID"));
if (namespaceID != 0 && nsId != 0 && namespaceID != nsId) {
throw new InconsistentFSStateException(sd.root,
"namespaceID is incompatible with others.");
}
namespaceID = nsId;
}
public void setServiceLayoutVersion(int lv) {
this.layoutVersion = lv;
}
public int getServiceLayoutVersion() {
return storageType == NodeType.DATA_NODE
? DataNodeLayoutVersion.getCurrentLayoutVersion()
: HdfsServerConstants.NAMENODE_LAYOUT_VERSION;
}
public Map<Integer, SortedSet<LayoutFeature>> getServiceLayoutFeatureMap() {
return storageType == NodeType.DATA_NODE? DataNodeLayoutVersion.FEATURES
: NameNodeLayoutVersion.FEATURES;
}
protected static String getProperty(Properties props, StorageDirectory sd,
String name) throws InconsistentFSStateException {
String property = props.getProperty(name);
if (property == null) {
throw new InconsistentFSStateException(sd.root, "file "
+ STORAGE_FILE_VERSION + " has " + name + " missing.");
}
return property;
}
public static Properties readPropertiesFile(File from) throws IOException {
if (from == null) {
return null;
}
RandomAccessFile file = new RandomAccessFile(from, "rws");
FileInputStream in = null;
Properties props = new Properties();
try {
in = new FileInputStream(file.getFD());
file.seek(0);
props.load(in);
} finally {
if (in != null) {
in.close();
}
file.close();
}
return props;
}
}
|
StorageInfo
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringRestToolKit.java
|
{
"start": 2958,
"end": 8024
}
|
class ____ implements RestToolKit {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringRestToolKit.class);
private final Map<MethodParameterMeta, TypeDescriptor> cache = CollectionUtils.newConcurrentHashMap();
private final ConfigurableBeanFactory beanFactory;
private final PropertyPlaceholderHelper placeholderHelper;
private final ConfigurationWrapper configuration;
private final ConversionService conversionService;
private final TypeConverter typeConverter;
private final BeanArgumentBinder argumentBinder;
private final ParameterNameReader parameterNameReader;
private final CompositeArgumentResolver argumentResolver;
public SpringRestToolKit(FrameworkModel frameworkModel) {
ApplicationModel applicationModel = frameworkModel.defaultApplication();
SpringExtensionInjector injector = SpringExtensionInjector.get(applicationModel);
ApplicationContext context = injector.getContext();
if (context instanceof ConfigurableApplicationContext) {
beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory();
placeholderHelper = null;
configuration = null;
} else {
beanFactory = null;
placeholderHelper = new PropertyPlaceholderHelper("${", "}", ":", true);
configuration = new ConfigurationWrapper(applicationModel);
}
if (context != null && context.containsBean("mvcConversionService")) {
conversionService = context.getBean("mvcConversionService", ConversionService.class);
} else {
conversionService = DefaultConversionService.getSharedInstance();
}
typeConverter = frameworkModel.getOrRegisterBean(GeneralTypeConverter.class);
parameterNameReader = frameworkModel.getOrRegisterBean(DefaultParameterNameReader.class);
argumentResolver = frameworkModel.getOrRegisterBean(CompositeArgumentResolver.class);
argumentBinder = new BeanArgumentBinder(argumentResolver, conversionService);
}
@Override
public int getDialect() {
return RestConstants.DIALECT_SPRING_MVC;
}
@Override
public String resolvePlaceholders(String text) {
if (!RestUtils.hasPlaceholder(text)) {
return text;
}
if (beanFactory != null) {
return beanFactory.resolveEmbeddedValue(text);
}
return placeholderHelper.replacePlaceholders(text, configuration);
}
@Override
public Object convert(Object value, ParameterMeta parameter) {
boolean tried = false;
if (value instanceof Collection || value instanceof Map) {
tried = true;
Object target = typeConverter.convert(value, parameter.getGenericType());
if (target != null) {
return target;
}
}
if (parameter instanceof MethodParameterMeta) {
TypeDescriptor targetType = cache.computeIfAbsent(
(MethodParameterMeta) parameter,
k -> new TypeDescriptor(new MethodParameter(k.getMethod(), k.getIndex())));
TypeDescriptor sourceType = TypeDescriptor.forObject(value);
if (conversionService.canConvert(sourceType, targetType)) {
try {
return conversionService.convert(value, sourceType, targetType);
} catch (Throwable t) {
LOGGER.debug(
"Spring convert value '{}' from type [{}] to type [{}] failed",
value,
value.getClass(),
parameter.getGenericType(),
t);
}
}
}
Object target = tried ? null : typeConverter.convert(value, parameter.getGenericType());
if (target == null && value != null) {
throw new RestException(
Messages.ARGUMENT_CONVERT_ERROR,
parameter.getName(),
value,
value.getClass(),
parameter.getGenericType());
}
return target;
}
@Override
public Object bind(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
return argumentBinder.bind(parameter, request, response);
}
@Override
public NamedValueMeta getNamedValueMeta(ParameterMeta parameter) {
return argumentResolver.getNamedValueMeta(parameter);
}
@Override
public String[] getParameterNames(Method method) {
return parameterNameReader.readParameterNames(method);
}
@Override
public String[] getParameterNames(Constructor<?> ctor) {
return parameterNameReader.readParameterNames(ctor);
}
@Override
public Map<String, Object> getAttributes(AnnotatedElement element, Annotation annotation) {
return AnnotatedElementUtils.getMergedAnnotationAttributes(element, annotation.annotationType());
}
}
|
SpringRestToolKit
|
java
|
apache__kafka
|
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
|
{
"start": 19637,
"end": 19765
}
|
class ____ {
private static final int METADATA_REFRESH_INTERVAL_MS = Integer.MAX_VALUE;
private static
|
GroupMetadataManager
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_3807/Issue3807Mapper.java
|
{
"start": 501,
"end": 737
}
|
class ____ {
private final String value;
public Source(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
//CHECKSTYLE:OFF
|
Source
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaPrimitiveIdTest.java
|
{
"start": 2205,
"end": 2354
}
|
class ____ {
@Id
private long id;
private String name;
public MyEntity() {
}
public MyEntity(long id) {
this.id = id;
}
}
}
|
MyEntity
|
java
|
google__guava
|
android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
|
{
"start": 1369,
"end": 1625
}
|
class ____ violates the specification of its supertype {@code
* DataInput}, which explicitly requires big-endian byte order.
*
* @author Chris Nokleberg
* @author Keith Bottner
* @since 8.0
*/
@J2ktIncompatible
@GwtIncompatible
public final
|
intentionally
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java
|
{
"start": 1901,
"end": 3488
}
|
class ____ {
@Test
void isAsyncStarted() {
assertThat(asyncRequest.isAsyncStarted()).isFalse();
asyncRequest.startAsync();
assertThat(asyncRequest.isAsyncStarted()).isTrue();
}
@Test
void startAsync() {
asyncRequest.startAsync();
MockAsyncContext context = (MockAsyncContext) request.getAsyncContext();
assertThat(context).isNotNull();
assertThat(context.getTimeout()).as("Timeout value not set").isEqualTo((44 * 1000));
assertThat(context.getListeners()).containsExactly(asyncRequest);
}
@Test
void startAsyncMultipleTimes() {
asyncRequest.startAsync();
asyncRequest.startAsync();
asyncRequest.startAsync();
asyncRequest.startAsync();
MockAsyncContext context = (MockAsyncContext) request.getAsyncContext();
assertThat(context).isNotNull();
assertThat(context.getListeners()).hasSize(1);
}
@Test
void startAsyncNotSupported() {
request.setAsyncSupported(false);
assertThatIllegalStateException()
.isThrownBy(asyncRequest::startAsync)
.withMessageContaining("Async support must be enabled");
}
@Test
void startAsyncAfterCompleted() throws Exception {
asyncRequest.startAsync();
asyncRequest.onComplete(new AsyncEvent(new MockAsyncContext(request, response)));
assertThatIllegalStateException()
.isThrownBy(asyncRequest::startAsync)
.withMessage("Cannot start async: [COMPLETED]");
}
@Test
void startAsyncAndSetTimeout() {
asyncRequest.startAsync();
assertThatIllegalStateException().isThrownBy(() -> asyncRequest.setTimeout(25L));
}
}
@Nested
|
StartAsync
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/codec/tsdb/ES87TSDBDocValuesFormatTests.java
|
{
"start": 2119,
"end": 2366
}
|
class ____ extends BaseDocValuesFormatTestCase {
private static final int NUM_DOCS = 10;
static {
LogConfigurator.loadLog4jPlugins();
LogConfigurator.configureESLogging();
}
public static
|
ES87TSDBDocValuesFormatTests
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/operators/SlotSharingGroup.java
|
{
"start": 6652,
"end": 10553
}
|
class ____ {
private String name;
private CPUResource cpuCores;
private MemorySize taskHeapMemory;
private MemorySize taskOffHeapMemory;
private MemorySize managedMemory;
private Map<String, Double> externalResources = new HashMap<>();
private Builder(String name) {
this.name = name;
}
/** Set the CPU cores for this SlotSharingGroup. */
public Builder setCpuCores(double cpuCores) {
checkArgument(cpuCores > 0, "The cpu cores should be positive.");
this.cpuCores = new CPUResource(cpuCores);
return this;
}
/** Set the task heap memory for this SlotSharingGroup. */
public Builder setTaskHeapMemory(MemorySize taskHeapMemory) {
checkArgument(
taskHeapMemory.compareTo(MemorySize.ZERO) > 0,
"The task heap memory should be positive.");
this.taskHeapMemory = taskHeapMemory;
return this;
}
/** Set the task heap memory for this SlotSharingGroup in MB. */
public Builder setTaskHeapMemoryMB(int taskHeapMemoryMB) {
checkArgument(taskHeapMemoryMB > 0, "The task heap memory should be positive.");
this.taskHeapMemory = MemorySize.ofMebiBytes(taskHeapMemoryMB);
return this;
}
/** Set the task off-heap memory for this SlotSharingGroup. */
public Builder setTaskOffHeapMemory(MemorySize taskOffHeapMemory) {
this.taskOffHeapMemory = taskOffHeapMemory;
return this;
}
/** Set the task off-heap memory for this SlotSharingGroup in MB. */
public Builder setTaskOffHeapMemoryMB(int taskOffHeapMemoryMB) {
this.taskOffHeapMemory = MemorySize.ofMebiBytes(taskOffHeapMemoryMB);
return this;
}
/** Set the task managed memory for this SlotSharingGroup. */
public Builder setManagedMemory(MemorySize managedMemory) {
this.managedMemory = managedMemory;
return this;
}
/** Set the task managed memory for this SlotSharingGroup in MB. */
public Builder setManagedMemoryMB(int managedMemoryMB) {
this.managedMemory = MemorySize.ofMebiBytes(managedMemoryMB);
return this;
}
/**
* Add the given external resource. The old value with the same resource name will be
* replaced if present.
*/
public Builder setExternalResource(String name, double value) {
this.externalResources.put(name, value);
return this;
}
/** Build the SlotSharingGroup. */
public SlotSharingGroup build() {
if (cpuCores != null && taskHeapMemory != null) {
taskOffHeapMemory = Optional.ofNullable(taskOffHeapMemory).orElse(MemorySize.ZERO);
managedMemory = Optional.ofNullable(managedMemory).orElse(MemorySize.ZERO);
return new SlotSharingGroup(
name,
cpuCores,
taskHeapMemory,
taskOffHeapMemory,
managedMemory,
externalResources);
} else if (cpuCores != null
|| taskHeapMemory != null
|| taskOffHeapMemory != null
|| managedMemory != null
|| !externalResources.isEmpty()) {
throw new IllegalArgumentException(
"The cpu cores and task heap memory are required when specifying the resource of a slot sharing group. "
+ "You need to explicitly configure them with positive value.");
} else {
return new SlotSharingGroup(name);
}
}
}
}
|
Builder
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_9.java
|
{
"start": 1169,
"end": 2326
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT `group`.* FROM `group` WHERE (group.group_id=159754)";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
SQLSelectStatement selectStmt = (SQLSelectStatement) stmt;
SQLSelect select = selectStmt.getSelect();
assertNotNull(select.getQuery());
MySqlSelectQueryBlock queryBlock = (MySqlSelectQueryBlock) select.getQuery();
assertNull(queryBlock.getOrderBy());
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
assertEquals(1, visitor.getTables().size());
assertEquals(2, visitor.getColumns().size());
assertEquals(1, visitor.getConditions().size());
assertEquals(0, visitor.getOrderByColumns().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("group")));
}
}
|
MySqlSelectTest_9
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/ValuesDoubleAggregator.java
|
{
"start": 1620,
"end": 1805
}
|
class ____ generated. Edit @{code X-ValuesAggregator.java.st} instead
* of this file.
*/
@Aggregator({ @IntermediateState(name = "values", type = "DOUBLE_BLOCK") })
@GroupingAggregator
|
is
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/javadoc/EmptyBlockTag.java
|
{
"start": 3308,
"end": 4973
}
|
class ____ extends DocTreePathScanner<Void, Void> {
private final VisitorState state;
private EmptyBlockTagChecker(VisitorState state) {
this.state = state;
}
@Override
public Void visitParam(ParamTree paramTree, Void unused) {
reportMatchIfEmpty(paramTree, paramTree.getDescription());
return super.visitParam(paramTree, null);
}
@Override
public Void visitReturn(ReturnTree returnTree, Void unused) {
reportMatchIfEmpty(returnTree, returnTree.getDescription());
return super.visitReturn(returnTree, null);
}
@Override
public Void visitThrows(ThrowsTree throwsTree, Void unused) {
reportMatchIfEmpty(throwsTree, throwsTree.getDescription());
return super.visitThrows(throwsTree, null);
}
@Override
public Void visitDeprecated(DeprecatedTree deprecatedTree, Void unused) {
reportMatchIfEmpty(deprecatedTree, deprecatedTree.getBody());
return super.visitDeprecated(deprecatedTree, null);
}
private void reportMatchIfEmpty(
BlockTagTree blockTagTree, List<? extends DocTree> description) {
if (description.isEmpty()) {
state.reportMatch(
describeMatch(
diagnosticPosition(getCurrentPath(), state),
// Don't generate a fix for deprecated; this will be annoying in conjunction with
// the check which requires a @deprecated tag for @Deprecated elements.
blockTagTree.getTagName().equals("deprecated")
? SuggestedFix.emptyFix()
: Utils.replace(blockTagTree, "", state)));
}
}
}
}
|
EmptyBlockTagChecker
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/catalog/SuggestionStrategy.java
|
{
"start": 940,
"end": 1311
}
|
interface ____ {
/**
* Provides a list of valid option names for a did you mean function.
*
* @param names valid names
* @param unknownOption unknown option name
* @return an array of suggested names (did you mean)
*/
String[] suggestEndpointOptions(Set<String> names, String unknownOption);
}
|
SuggestionStrategy
|
java
|
hibernate__hibernate-orm
|
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/function/json/SingleStoreJsonMergepatchFunction.java
|
{
"start": 554,
"end": 1279
}
|
class ____ extends AbstractJsonMergepatchFunction {
public SingleStoreJsonMergepatchFunction(TypeConfiguration typeConfiguration) {
super( typeConfiguration );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> translator) {
final int argumentCount = arguments.size();
for ( int i = 0; i < argumentCount - 1; i++ ) {
sqlAppender.appendSql( "json_merge_patch(" );
}
arguments.get( 0 ).accept( translator );
for ( int i = 1; i < argumentCount; i++ ) {
sqlAppender.appendSql( ',' );
arguments.get( i ).accept( translator );
sqlAppender.appendSql( ')' );
}
}
}
|
SingleStoreJsonMergepatchFunction
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy-client/deployment/src/main/java/io/quarkus/restclient/deployment/RestClientPredicateProviderBuildItem.java
|
{
"start": 253,
"end": 1021
}
|
class ____ extends MultiBuildItem {
private final String providerClass;
private final Predicate<ClassInfo> matcher;
/**
* Register JAX-RS client provider against Rest clients matching {@code matcher} condition.
*/
public RestClientPredicateProviderBuildItem(String providerClass, Predicate<ClassInfo> matcher) {
this.providerClass = providerClass;
this.matcher = matcher;
}
public String getProviderClass() {
return providerClass;
}
/**
* Test whether the {@link #providerClass} should be added to {@code restClientClassInfo} as provider.
*/
boolean appliesTo(ClassInfo restClientClassInfo) {
return matcher.test(restClientClassInfo);
}
}
|
RestClientPredicateProviderBuildItem
|
java
|
apache__camel
|
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTextlineInOutNonBlockingTest.java
|
{
"start": 1179,
"end": 3854
}
|
class ____ extends BaseNettyTest {
private static String beforeThreadName;
private static String afterThreadName;
private static String beforeThreadName2;
private static String afterThreadName2;
@Test
public void testNonBlocking() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
String reply = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", reply);
MockEndpoint.assertIsSatisfied(context);
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should not same threads");
assertFalse(beforeThreadName2.equalsIgnoreCase(afterThreadName2), "Should not same threads");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("log:before")
.process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
})
.to("netty:tcp://localhost:{{port}}?textline=true&sync=true")
.process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
})
.to("log:after")
.to("mock:result");
from("netty:tcp://localhost:{{port}}?textline=true&sync=true")
.process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName2 = Thread.currentThread().getName();
}
})
// body should be a String when using textline codec
.validate(body().isInstanceOf(String.class))
// async delayed is non blocking
.delay(100).asyncDelayed()
.process(new Processor() {
public void process(Exchange exchange) {
afterThreadName2 = Thread.currentThread().getName();
}
})
.transform(body().regexReplaceAll("Hello", "Bye"));
}
};
}
}
|
NettyTextlineInOutNonBlockingTest
|
java
|
hibernate__hibernate-orm
|
hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/HolidayCalendar.java
|
{
"start": 319,
"end": 1399
}
|
class ____ {
private Long id;
private String name;
// Date -> String
private Map holidays = new HashMap();
public HolidayCalendar init() {
name = "default";
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
try {
holidays.clear();
holidays.put(df.parse("2009.01.01"), "New Year's Day");
holidays.put(df.parse("2009.02.14"), "Valentine's Day");
holidays.put(df.parse("2009.11.11"), "Armistice Day");
} catch (ParseException e) {
throw new RuntimeException(e);
}
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getHolidays() {
return holidays;
}
protected void setHolidays(Map holidays) {
this.holidays = holidays;
}
public void addHoliday(Date d, String name) {
holidays.put(d, name);
}
public String getHoliday(Date d) {
return (String)holidays.get(d);
}
public boolean isHoliday(Date d) {
return holidays.containsKey(d);
}
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
}
|
HolidayCalendar
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/diskbalancer/DiskBalancerConstants.java
|
{
"start": 1095,
"end": 1530
}
|
class ____ {
public static final String DISKBALANCER_BANDWIDTH = "DiskBalancerBandwidth";
public static final String DISKBALANCER_VOLUME_NAME =
"DiskBalancerVolumeName";
/** Min and Max Plan file versions that we know of. **/
public static final int DISKBALANCER_MIN_VERSION = 1;
public static final int DISKBALANCER_MAX_VERSION = 1;
// never constructed.
private DiskBalancerConstants() {
}
}
|
DiskBalancerConstants
|
java
|
elastic__elasticsearch
|
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/slack/message/Action.java
|
{
"start": 3354,
"end": 5962
}
|
class ____ implements ToXContent {
private TextTemplate type;
private TextTemplate name;
private TextTemplate text;
private TextTemplate url;
private TextTemplate style;
public Action render(TextTemplateEngine engine, Map<String, Object> model) {
String style = engine.render(this.style, model);
String type = engine.render(this.type, model);
String url = engine.render(this.url, model);
String name = engine.render(this.name, model);
String text = engine.render(this.text, model);
return new Action(style, name, type, text, url);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Template template = (Template) o;
return Objects.equals(style, template.style)
&& Objects.equals(type, template.type)
&& Objects.equals(url, template.url)
&& Objects.equals(text, template.text)
&& Objects.equals(name, template.name);
}
@Override
public int hashCode() {
return Objects.hash(style, type, url, name, text);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject()
.field(NAME.getPreferredName(), name)
.field(STYLE.getPreferredName(), style)
.field(TYPE.getPreferredName(), type)
.field(TEXT.getPreferredName(), text)
.field(URL.getPreferredName(), url)
.endObject();
}
public TextTemplate getType() {
return type;
}
public void setType(TextTemplate type) {
this.type = type;
}
public TextTemplate getName() {
return name;
}
public void setName(TextTemplate name) {
this.name = name;
}
public TextTemplate getText() {
return text;
}
public void setText(TextTemplate text) {
this.text = text;
}
public TextTemplate getUrl() {
return url;
}
public void setUrl(TextTemplate url) {
this.url = url;
}
public TextTemplate getStyle() {
return style;
}
public void setStyle(TextTemplate style) {
this.style = style;
}
}
}
|
Template
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/connection/DNSMonitor.java
|
{
"start": 1323,
"end": 10838
}
|
class ____ {
private static final Logger log = LoggerFactory.getLogger(DNSMonitor.class);
private final AddressResolver<InetSocketAddress> resolver;
private final ConnectionManager connectionManager;
private final Map<RedisURI, InetSocketAddress> masters = new HashMap<>();
private final Map<RedisURI, InetSocketAddress> slaves = new HashMap<>();
private volatile Timeout dnsMonitorFuture;
private final long dnsMonitoringInterval;
private boolean printed;
public DNSMonitor(ConnectionManager connectionManager, RedisClient masterHost, Collection<RedisURI> slaveHosts, long dnsMonitoringInterval, AddressResolverGroup<InetSocketAddress> resolverGroup) {
this.resolver = resolverGroup.getResolver(connectionManager.getServiceManager().getGroup().next());
masterHost.resolveAddr().join();
masters.put(masterHost.getConfig().getAddress(), masterHost.getAddr());
for (RedisURI host : slaveHosts) {
Future<InetSocketAddress> resolveFuture = resolver.resolve(InetSocketAddress.createUnresolved(host.getHost(), host.getPort()));
resolveFuture.syncUninterruptibly();
slaves.put(host, resolveFuture.getNow());
}
this.connectionManager = connectionManager;
this.dnsMonitoringInterval = dnsMonitoringInterval;
}
public void start() {
monitorDnsChange();
log.debug("DNS monitoring enabled; Current masters: {}, slaves: {}", masters, slaves);
}
public void stop() {
if (dnsMonitorFuture != null) {
dnsMonitorFuture.cancel();
}
}
private void monitorDnsChange() {
dnsMonitorFuture = connectionManager.getServiceManager().newTimeout(t -> {
if (connectionManager.getServiceManager().isShuttingDown()) {
return;
}
CompletableFuture<Void> mf = monitorMasters();
CompletableFuture<Void> sf = monitorSlaves();
CompletableFuture.allOf(mf, sf)
.whenComplete((r, e) -> monitorDnsChange());
}, dnsMonitoringInterval, TimeUnit.MILLISECONDS);
}
private CompletableFuture<Void> monitorMasters() {
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Entry<RedisURI, InetSocketAddress> entry : masters.entrySet()) {
CompletableFuture<Void> promise = new CompletableFuture<>();
futures.add(promise);
CompletableFuture<List<RedisURI>> ipsFuture = connectionManager.getServiceManager().resolveAll(entry.getKey());
ipsFuture.whenComplete((addresses, ex) -> {
if (ex != null) {
log.error("Unable to resolve {}", entry.getKey().getHost(), ex);
promise.complete(null);
return;
}
if (addresses.size() > 1) {
if (!printed) {
log.warn("Use Redisson PRO version (https://redisson.pro/feature-comparison.html) with Proxy mode feature to utilize all ip addresses: {} resolved by: {}",
addresses, entry.getKey());
printed = true;
}
}
for (RedisURI address : addresses) {
if (address.equals(entry.getValue())) {
log.debug("{} resolved to {}", entry.getKey().getHost(), addresses);
promise.complete(null);
return;
}
}
int index = 0;
if (addresses.size() > 1) {
addresses.sort(Comparator.comparing(RedisURI::getHost));
}
RedisURI address = addresses.get(index);
log.debug("{} resolved to {} and {} selected", entry.getKey().getHost(), addresses, address);
try {
InetSocketAddress currentMasterAddr = entry.getValue();
byte[] addr = NetUtil.createByteArrayFromIpAddressString(address.getHost());
InetSocketAddress newMasterAddr = new InetSocketAddress(InetAddress.getByAddress(entry.getKey().getHost(), addr), address.getPort());
if (!address.equals(currentMasterAddr)) {
log.info("Detected DNS change. Master {} has changed ip from {} to {}",
entry.getKey(), currentMasterAddr.getAddress().getHostAddress(),
newMasterAddr.getAddress().getHostAddress());
MasterSlaveEntry masterSlaveEntry = connectionManager.getEntry(currentMasterAddr);
if (masterSlaveEntry == null) {
log.error("Unable to find entry for current master {}", currentMasterAddr);
promise.complete(null);
return;
}
CompletableFuture<RedisClient> changeFuture = masterSlaveEntry.changeMaster(newMasterAddr, entry.getKey());
changeFuture.whenComplete((r, e) -> {
promise.complete(null);
if (e == null) {
masters.put(entry.getKey(), newMasterAddr);
}
});
} else {
promise.complete(null);
}
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
promise.complete(null);
}
});
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
private CompletableFuture<Void> monitorSlaves() {
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Entry<RedisURI, InetSocketAddress> entry : slaves.entrySet()) {
CompletableFuture<Void> promise = new CompletableFuture<>();
futures.add(promise);
log.debug("Request sent to resolve ip address for slave host: {}", entry.getKey().getHost());
Future<InetSocketAddress> resolveFuture = resolver.resolve(InetSocketAddress.createUnresolved(entry.getKey().getHost(), entry.getKey().getPort()));
resolveFuture.addListener((FutureListener<InetSocketAddress>) future -> {
if (!future.isSuccess()) {
log.error("Unable to resolve {}", entry.getKey().getHost(), future.cause());
promise.complete(null);
return;
}
log.debug("Resolved ip: {} for slave host: {}", future.getNow().getAddress(), entry.getKey().getHost());
InetSocketAddress currentSlaveAddr = entry.getValue();
InetSocketAddress newSlaveAddr = future.getNow();
if (!newSlaveAddr.getAddress().equals(currentSlaveAddr.getAddress())) {
log.info("Detected DNS change. Slave {} has changed ip from {} to {}",
entry.getKey().getHost(), currentSlaveAddr.getAddress().getHostAddress(), newSlaveAddr.getAddress().getHostAddress());
boolean slaveFound = false;
for (MasterSlaveEntry masterSlaveEntry : connectionManager.getEntrySet()) {
if (!masterSlaveEntry.hasSlave(currentSlaveAddr)) {
continue;
}
slaveFound = true;
if (masterSlaveEntry.hasSlave(newSlaveAddr)) {
CompletableFuture<Boolean> slaveUpFuture = masterSlaveEntry.slaveUpAsync(newSlaveAddr);
slaveUpFuture.whenComplete((r, e) -> {
if (e != null) {
promise.complete(null);
return;
}
if (r) {
slaves.put(entry.getKey(), newSlaveAddr);
masterSlaveEntry.slaveDown(currentSlaveAddr);
}
promise.complete(null);
});
} else {
CompletableFuture<Void> addFuture = masterSlaveEntry.addSlave(newSlaveAddr, entry.getKey());
addFuture.whenComplete((res, e) -> {
if (e != null) {
log.error("Can't add slave: {}", newSlaveAddr, e);
promise.complete(null);
return;
}
slaves.put(entry.getKey(), newSlaveAddr);
masterSlaveEntry.slaveDown(currentSlaveAddr);
promise.complete(null);
});
}
break;
}
if (!slaveFound) {
promise.complete(null);
}
} else {
promise.complete(null);
}
});
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
}
|
DNSMonitor
|
java
|
netty__netty
|
codec-http2/src/test/java/io/netty/handler/codec/http2/LastInboundHandler.java
|
{
"start": 6397,
"end": 6528
}
|
class ____ {
private final Object evt;
UserEvent(Object evt) {
this.evt = evt;
}
}
}
|
UserEvent
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/example/type/AssignableTypeFilterTestsTypes.java
|
{
"start": 1411,
"end": 1472
}
|
class ____ implements JdbcDaoSupport {
}
}
|
SimpleJdbcDaoSupport
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/fastjson/serializer/issue3479/TestIssue3479.java
|
{
"start": 320,
"end": 597
}
|
class ____ {
private String typeKey;
public String getTypeKey() {
return typeKey;
}
public void setTypeKey(String typeKey) {
this.typeKey = typeKey;
}
}
@JSONType(typeName = "dog")
public static
|
Animal
|
java
|
spring-projects__spring-security
|
config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java
|
{
"start": 2005,
"end": 2749
}
|
class ____ implements RequestMatcher {
private String processUrl;
private ExactUrlRequestMatcher(String processUrl) {
this.processUrl = processUrl;
}
@Override
public boolean matches(HttpServletRequest request) {
String uri = request.getRequestURI();
String query = request.getQueryString();
if (query != null) {
uri += "?" + query;
}
if ("".equals(request.getContextPath())) {
return uri.equals(this.processUrl);
}
return uri.equals(request.getContextPath() + this.processUrl);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ExactUrl [processUrl='").append(this.processUrl).append("']");
return sb.toString();
}
}
}
|
ExactUrlRequestMatcher
|
java
|
apache__camel
|
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/holder/MyOrderType.java
|
{
"start": 1046,
"end": 1128
}
|
class ____ {
@XmlElement(required = true)
protected int iAmount;
}
|
MyOrderType
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/support/DirtiesContextTestExecutionListenerTests.java
|
{
"start": 17057,
"end": 17181
}
|
class ____ {
void test() {
}
}
@DirtiesContext(classMode = AFTER_CLASS)
static
|
DirtiesContextDeclaredLocallyBeforeClass
|
java
|
apache__camel
|
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/multibytes/BindyMultiBytesTest.java
|
{
"start": 1523,
"end": 3479
}
|
class ____ extends CamelTestSupport {
@Produce("direct:in")
private ProducerTemplate producer;
@EndpointInject("mock:result")
private MockEndpoint result;
// *************************************************************************
// TESTS
// *************************************************************************
/**
* Let's assume we want to read the content of a 10 bytes record from an UTF-8 encoded file. test string takes 10
* bytes with 9 characters (2 char = 3 bytes content + padding). I assume to be able to read 9 char string from this
* 10 bytes fixed length record with bindy.
*/
@Test
public void testMultiBytes() throws Exception {
String test = "a\u00DF ";
assertEquals(10, test.length(), "Should be 10 length");
byte[] testAsBytes = test.getBytes(StandardCharsets.UTF_8);
assertEquals(11, testAsBytes.length, "A\u00DF takes 11 bytes, because \u00DF takes 2");
result.expectedMessagesMatches(exchange -> test.equals(exchange.getIn().getBody(TestRecord.class).getField1()));
producer.sendBody(test);
result.assertIsSatisfied();
}
// *************************************************************************
// ROUTES
// *************************************************************************
@Override
protected RouteBuilder createRouteBuilder() {
RouteBuilder routeBuilder = new RouteBuilder() {
@Override
public void configure() {
from("direct:in")
.setHeader(Exchange.CHARSET_NAME, constant(StandardCharsets.UTF_8.name()))
.unmarshal(new BindyFixedLengthDataFormat(TestRecord.class))
.to("mock:result");
}
};
return routeBuilder;
}
@FixedLengthRecord(length = 10, paddingChar = ' ')
public static
|
BindyMultiBytesTest
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicAuthTest.java
|
{
"start": 840,
"end": 3220
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Resource.class)
.addAsResource("application-basic-auth.properties", "application.properties")
.addAsResource("test-users.properties")
.addAsResource("test-roles.properties"));
@TestHTTPResource
URI baseUri;
@Test
public void ensureBasicAuthSetupProperly() {
when().get("/open").then().statusCode(200);
when().get("/secured").then().statusCode(401);
given().auth().preemptive().basic("foo", "bar").when().get("/open").then().statusCode(401);
given().auth().preemptive().basic("foo", "bar").when().get("/secured").then().statusCode(401);
given().auth().preemptive().basic("jdoe", "p4ssw0rd").when().get("/open").then().statusCode(200);
given().auth().preemptive().basic("jdoe", "p4ssw0rd").when().get("/secured").then().statusCode(403);
given().auth().preemptive().basic("stuart", "test").when().get("/open").then().statusCode(200);
given().auth().preemptive().basic("stuart", "test").when().get("/secured").then().statusCode(200);
}
@Test
public void testInvalidCredentials() {
InvalidCredentials client = RestClientBuilder.newBuilder().baseUri(baseUri).build(InvalidCredentials.class);
assertThatThrownBy(client::open).isInstanceOf(WebApplicationException.class).hasMessageContaining("401");
assertThatThrownBy(client::secured).isInstanceOf(WebApplicationException.class).hasMessageContaining("401");
}
@Test
public void testNoRoleUser() {
NoRoleUser client = RestClientBuilder.newBuilder().baseUri(baseUri).build(NoRoleUser.class);
assertThat(client.open()).isEqualTo("ok");
assertThatThrownBy(client::secured).isInstanceOf(WebApplicationException.class).hasMessageContaining("403");
}
@Test
public void testAdminUser() {
AdminUser client = RestClientBuilder.newBuilder().baseUri(baseUri).build(AdminUser.class);
assertThat(client.open()).isEqualTo("ok");
assertThat(client.secured()).isEqualTo("ok");
}
@ClientBasicAuth(username = "foo", password = "bar")
@ClientHeaderParam(name = "whatever", value = "test")
public
|
BasicAuthTest
|
java
|
quarkusio__quarkus
|
extensions/elytron-security-ldap/deployment/src/test/java/io/quarkus/elytron/security/ldap/rest/RolesEndpointClassLevel.java
|
{
"start": 291,
"end": 366
}
|
class ____
*/
@Path("/roles-class")
@RolesAllowed("standardRole")
public
|
level
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/SeenGroupIds.java
|
{
"start": 405,
"end": 1203
}
|
interface ____ {
/**
* The grouping ids that have been seen already. This {@link BitArray} is
* kept and mutated by the caller so make a copy if it's something you
* need your own copy of it.
*/
BitArray seenGroupIds(BigArrays bigArrays);
record Empty() implements SeenGroupIds {
@Override
public BitArray seenGroupIds(BigArrays bigArrays) {
return new BitArray(1, bigArrays);
}
}
record Range(int from, int to) implements SeenGroupIds {
@Override
public BitArray seenGroupIds(BigArrays bigArrays) {
BitArray seen = new BitArray(to - from, bigArrays);
for (int i = from; i < to; i++) {
seen.set(i);
}
return seen;
}
}
}
|
SeenGroupIds
|
java
|
apache__camel
|
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpConsumerDisconnectIT.java
|
{
"start": 1365,
"end": 5071
}
|
class ____ extends SftpServerTestSupport {
private static final String SAMPLE_FILE_NAME_1
= String.format("sample-1-%s.txt", SftpConsumerDisconnectIT.class.getSimpleName());
private static final String SAMPLE_FILE_NAME_2
= String.format("sample-2-%s.txt", SftpConsumerDisconnectIT.class.getSimpleName());
private static final String SAMPLE_FILE_CHARSET = "iso-8859-1";
private static final String SAMPLE_FILE_PAYLOAD = "abc";
@Test
public void testConsumeDelete() throws Exception {
// prepare sample file to be consumed by SFTP consumer
createSampleFile(SAMPLE_FILE_NAME_1);
// Prepare expectations
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived(SAMPLE_FILE_PAYLOAD);
context.getRouteController().startRoute("foo");
// Check that expectations are satisfied
MockEndpoint.assertIsSatisfied(context);
// File is deleted
File deletedFile = new File(service.getFtpRootDir() + "/" + SAMPLE_FILE_NAME_1);
await().atMost(250, TimeUnit.MILLISECONDS)
.untilAsserted(() -> assertFalse(deletedFile.exists(), "File should have been deleted: " + deletedFile));
}
@Test
public void testConsumeMove() throws Exception {
// moved file after its processed
String movedFile = ftpFile(".camel/") + SAMPLE_FILE_NAME_2;
// prepare sample file to be consumed by SFTP consumer
createSampleFile(SAMPLE_FILE_NAME_2);
// Prepare expectations
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived(SAMPLE_FILE_PAYLOAD);
// use mock to assert that the file will be moved there eventually
mock.expectedFileExists(movedFile);
context.getRouteController().startRoute("bar");
// Check that expectations are satisfied
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}"
+ "?username=admin&password=admin&delete=true&knownHostsFile="
+ service.getKnownHostsFile())
.routeId("foo").noAutoStartup().process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
service.disconnectAllSessions(); // disconnect all Sessions from
// the SFTP server
}
}).to("mock:result");
from("sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}"
+ "?username=admin&password=admin&noop=false&move=.camel").routeId("bar").noAutoStartup()
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
service.disconnectAllSessions(); // disconnect all Sessions
// from the SFTP server
}
}).to("mock:result");
}
};
}
private void createSampleFile(String fileName) throws IOException {
File file = new File(service.getFtpRootDir() + "/" + fileName);
FileUtils.write(file, SAMPLE_FILE_PAYLOAD, SAMPLE_FILE_CHARSET);
}
}
|
SftpConsumerDisconnectIT
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java
|
{
"start": 4000,
"end": 10294
}
|
class ____ implements HandlerMethodReturnValueHandler {
private final List<HttpMessageConverter<?>> sseMessageConverters;
private final ReactiveTypeHandler reactiveHandler;
private final List<ViewResolver> viewResolvers;
private final LocaleResolver localeResolver;
/**
* Simple constructor with reactive type support based on a default instance of
* {@link ReactiveAdapterRegistry},
* {@link org.springframework.core.task.SyncTaskExecutor}, and
* {@link ContentNegotiationManager} with an Accept header strategy.
*/
public ResponseBodyEmitterReturnValueHandler(List<HttpMessageConverter<?>> messageConverters) {
this(messageConverters,
ReactiveAdapterRegistry.getSharedInstance(), new SyncTaskExecutor(),
new ContentNegotiationManager());
}
/**
* Constructor that with added arguments to customize "reactive" type support.
* @param messageConverters converters to write emitted objects with
* @param registry for reactive return value type support
* @param executor for blocking I/O writes of items emitted from reactive types
* @param manager for detecting streaming media types
* @since 5.0
*/
public ResponseBodyEmitterReturnValueHandler(List<HttpMessageConverter<?>> messageConverters,
ReactiveAdapterRegistry registry, TaskExecutor executor, ContentNegotiationManager manager) {
this(messageConverters, registry, executor, manager, Collections.emptyList(), null);
}
/**
* Constructor that with added arguments for view rendering.
* @param messageConverters converters to write emitted objects with
* @param registry for reactive return value type support
* @param executor for blocking I/O writes of items emitted from reactive types
* @param manager for detecting streaming media types
* @param viewResolvers resolvers for fragment stream rendering
* @param localeResolver the {@link LocaleResolver} for fragment stream rendering
* @since 6.2
*/
public ResponseBodyEmitterReturnValueHandler(
List<HttpMessageConverter<?>> messageConverters,
ReactiveAdapterRegistry registry, TaskExecutor executor, ContentNegotiationManager manager,
List<ViewResolver> viewResolvers, @Nullable LocaleResolver localeResolver) {
Assert.notEmpty(messageConverters, "HttpMessageConverter List must not be empty");
this.sseMessageConverters = initSseConverters(messageConverters);
this.reactiveHandler = new ReactiveTypeHandler(registry, executor, manager, null);
this.viewResolvers = viewResolvers;
this.localeResolver = (localeResolver != null ? localeResolver : new AcceptHeaderLocaleResolver());
}
private static List<HttpMessageConverter<?>> initSseConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter.canWrite(String.class, MediaType.TEXT_PLAIN)) {
return converters;
}
}
List<HttpMessageConverter<?>> result = new ArrayList<>(converters.size() + 1);
result.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
result.addAll(converters);
return result;
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
Class<?> bodyType = ResponseEntity.class.isAssignableFrom(returnType.getParameterType()) ?
ResolvableType.forMethodParameter(returnType).getGeneric().resolve() :
returnType.getParameterType();
return (bodyType != null && supportsBodyType(bodyType));
}
boolean supportsBodyType(Class<?> bodyType) {
return (ResponseBodyEmitter.class.isAssignableFrom(bodyType) || this.reactiveHandler.isReactiveType(bodyType));
}
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
Assert.state(response != null, "No HttpServletResponse");
ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
MediaType contentType = null;
if (returnValue instanceof ResponseEntity<?> responseEntity) {
response.setStatus(responseEntity.getStatusCode().value());
outputMessage.getHeaders().putAll(responseEntity.getHeaders());
contentType = responseEntity.getHeaders().getContentType();
returnValue = responseEntity.getBody();
returnType = returnType.nested();
if (returnValue == null) {
mavContainer.setRequestHandled(true);
outputMessage.flush();
return;
}
}
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
Assert.state(request != null, "No ServletRequest");
ResponseBodyEmitter emitter;
if (returnValue instanceof ResponseBodyEmitter responseBodyEmitter) {
emitter = responseBodyEmitter;
}
else {
emitter = this.reactiveHandler.handleValue(returnValue, returnType, contentType, mavContainer, webRequest);
if (emitter == null) {
// We're not streaming; write headers without committing response
outputMessage.getHeaders().forEach((headerName, headerValues) -> {
for (String headerValue : headerValues) {
response.addHeader(headerName, headerValue);
}
});
return;
}
}
emitter.extendResponse(outputMessage);
// We are streaming
ShallowEtagHeaderFilter.disableContentCaching(request);
// Suppress header updates from message converters
outputMessage = new StreamingServletServerHttpResponse(outputMessage);
DefaultSseEmitterHandler emitterHandler;
try {
DeferredResult<?> result = new DeferredResult<>(emitter.getTimeout());
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer);
FragmentHandler handler = new FragmentHandler(request, response, this.viewResolvers, this.localeResolver);
emitterHandler = new DefaultSseEmitterHandler(this.sseMessageConverters, handler, outputMessage, result);
}
catch (Throwable ex) {
emitter.initializeWithError(ex);
throw ex;
}
emitter.initialize(emitterHandler);
}
/**
* Wrap to silently ignore header changes HttpMessageConverter's that would
* otherwise cause HttpHeaders to raise exceptions.
*/
private static
|
ResponseBodyEmitterReturnValueHandler
|
java
|
apache__camel
|
components/camel-twitter/src/main/java/org/apache/camel/component/twitter/timeline/TwitterTimelineEndpoint.java
|
{
"start": 2015,
"end": 4997
}
|
class ____ extends AbstractTwitterEndpoint {
@UriPath(description = "The timeline type to produce/consume.")
@Metadata(required = true)
private TimelineType timelineType;
@UriParam(description = "The username when using timelineType=user")
private String user;
@UriParam(description = "The list name when using timelineType=list")
private String list;
public TwitterTimelineEndpoint(String uri, String remaining, String user, String list, TwitterTimelineComponent component,
TwitterConfiguration properties) {
super(uri, component, properties);
if (remaining == null) {
throw new IllegalArgumentException(String.format("The timeline type must be specified for '%s'", uri));
}
this.timelineType = component.getCamelContext().getTypeConverter().convertTo(TimelineType.class, remaining);
this.user = user;
this.list = list;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getList() {
return list;
}
public void setList(String list) {
this.list = list;
}
@Override
public Producer createProducer() throws Exception {
if (timelineType != USER) {
throw new IllegalArgumentException(
"Cannot create any producer with uri " + getEndpointUri() +
". A producer type was not provided (or an incorrect pairing was used).");
}
return new UserProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
AbstractTwitterConsumerHandler handler = null;
switch (timelineType) {
case HOME:
handler = new HomeConsumerHandler(this);
break;
case MENTIONS:
handler = new MentionsConsumerHandler(this);
break;
case LIST:
handler = new UserListConsumerHandler(this, user, list);
break;
case USER:
if (user == null || user.isBlank()) {
throw new IllegalArgumentException("Fetch type set to USER TIMELINE but no user was set.");
} else {
handler = new UserConsumerHandler(this, user);
break;
}
default:
break;
}
if (handler != null) {
return TwitterHelper.createConsumer(processor, this, handler);
}
throw new IllegalArgumentException(
"Cannot create any consumer with uri " + getEndpointUri()
+ ". A consumer type was not provided (or an incorrect pairing was used).");
}
public TimelineType getTimelineType() {
return timelineType;
}
}
|
TwitterTimelineEndpoint
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KubernetesPodsComponentBuilderFactory.java
|
{
"start": 1415,
"end": 1956
}
|
interface ____ {
/**
* Kubernetes Pods (camel-kubernetes)
* Perform operations on Kubernetes Pods and get notified on Pod changes.
*
* Category: container,cloud
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-kubernetes
*
* @return the dsl builder
*/
static KubernetesPodsComponentBuilder kubernetesPods() {
return new KubernetesPodsComponentBuilderImpl();
}
/**
* Builder for the Kubernetes Pods component.
*/
|
KubernetesPodsComponentBuilderFactory
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/references/statics/BeerMapperWithNonUsedMapper.java
|
{
"start": 458,
"end": 1070
}
|
class ____ {
public static final BeerMapperWithNonUsedMapper INSTANCE = Mappers.getMapper( BeerMapperWithNonUsedMapper.class );
@Mapping( target = "category", source = "percentage")
public abstract BeerDto mapBeer(Beer beer);
public static Category toCategory(float in) {
if ( in < 2.5 ) {
return Category.LIGHT;
}
else if ( in < 5.5 ) {
return Category.LAGER;
}
else if ( in < 10 ) {
return Category.STRONG;
}
else {
return Category.BARLEY_WINE;
}
}
}
|
BeerMapperWithNonUsedMapper
|
java
|
apache__camel
|
components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultConstants.java
|
{
"start": 908,
"end": 1818
}
|
class ____ {
private static final String HEADER_PREFIX = "CamelHashicorpVault";
// headers set by the producer only
@Metadata(label = "producer", description = "Overrides the desired operation to be used in the producer.",
javaType = "String")
public static final String OPERATION = HEADER_PREFIX + "ProducerOperation";
// headers set by the producer only
@Metadata(label = "producer", description = "Set the desired secret path as header.",
javaType = "String")
public static final String SECRET_PATH = HEADER_PREFIX + "SecretPath";
// headers set by the producer only
@Metadata(label = "producer", description = "Set the desired secret version as header.",
javaType = "String")
public static final String SECRET_VERSION = HEADER_PREFIX + "SecretVersion";
private HashicorpVaultConstants() {
}
}
|
HashicorpVaultConstants
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MembersInjectionValidationTest.java
|
{
"start": 10560,
"end": 11562
}
|
interface ____ {",
" void inject(KotlinObjectWithMemberInjection injected);",
"}");
CompilerTests.daggerCompiler(component, testModule)
.compile(
subject -> {
subject.hasErrorCount(3);
subject.hasErrorContaining(
"Dagger does not support injection into static fields");
subject.hasErrorContaining("Dagger does not support injection into Kotlin objects");
subject.hasErrorContaining("KotlinObjectWithMemberInjection cannot be provided");
});
}
@Test
public void setterMemberInjectionForKotlinObjectFails() {
Source component =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.Component;",
"import dagger.internal.codegen.KotlinObjectWithSetterMemberInjection;",
"",
"@Component(modules = TestModule.class)",
"
|
TestComponent
|
java
|
playframework__playframework
|
dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/PatternPathParamTest.java
|
{
"start": 516,
"end": 944
}
|
class ____ extends AbstractRoutesTest {
@Test
public void checkPattern() {
var result = route(app, fakeRequest(GET, "/pattern/123"));
assertThat(result.status()).isEqualTo(OK);
assertThat(contentAsString(result)).isEqualTo("123");
// Invalid
result = route(app, fakeRequest(GET, "/pattern/abc"));
assertThat(result.status()).isEqualTo(NOT_FOUND);
}
}
|
PatternPathParamTest
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ProductionGraphValidationTest.java
|
{
"start": 3238,
"end": 3756
}
|
class ____ {}");
CompilerTests.daggerCompiler(EXECUTOR_MODULE, module, component, foo, bar)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"Bar cannot be provided without an @Inject constructor or an @Provides- or "
+ "@Produces-annotated method.")
.onSource(component)
.onLineContaining("
|
Bar
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/AbstractLayout.java
|
{
"start": 1342,
"end": 1469
}
|
class ____ Layouts.
*
* @param <T>
* The Class that the Layout will format the LogEvent into.
*/
public abstract
|
for
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java
|
{
"start": 21907,
"end": 24651
}
|
class ____ implements SpringApplicationHook {
private final Mode mode;
private final @Nullable ApplicationContextInitializer<ConfigurableApplicationContext> initializer;
private final Consumer<SpringApplication> configurer;
private final List<ApplicationContext> contexts = Collections.synchronizedList(new ArrayList<>());
private final List<ApplicationContext> failedContexts = Collections.synchronizedList(new ArrayList<>());
ContextLoaderHook(Mode mode,
@Nullable ApplicationContextInitializer<ConfigurableApplicationContext> initializer,
Consumer<SpringApplication> configurer) {
this.mode = mode;
this.initializer = initializer;
this.configurer = configurer;
}
@Override
public SpringApplicationRunListener getRunListener(SpringApplication application) {
return new SpringApplicationRunListener() {
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
ContextLoaderHook.this.configurer.accept(application);
if (ContextLoaderHook.this.mode == Mode.AOT_RUNTIME) {
Assert.state(ContextLoaderHook.this.initializer != null, "'initializer' must not be null");
application.addInitializers(
(AotApplicationContextInitializer<?>) ContextLoaderHook.this.initializer::initialize);
}
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
ContextLoaderHook.this.contexts.add(context);
if (ContextLoaderHook.this.mode == Mode.AOT_PROCESSING) {
throw new AbandonedRunException(context);
}
}
@Override
public void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) {
if (context != null) {
ContextLoaderHook.this.failedContexts.add(context);
}
}
};
}
private ApplicationContext runMain(Runnable action) throws Exception {
return run(() -> {
action.run();
return NONE;
});
}
private ApplicationContext run(ThrowingSupplier<?> action) throws Exception {
try {
Object result = SpringApplication.withHook(this, action);
if (result instanceof ApplicationContext context) {
return context;
}
}
catch (AbandonedRunException ex) {
// Ignore
}
catch (Exception ex) {
if (this.failedContexts.size() == 1) {
throw new ContextLoadException(this.failedContexts.get(0), ex);
}
throw ex;
}
List<ApplicationContext> rootContexts = this.contexts.stream()
.filter((context) -> context.getParent() == null)
.toList();
Assert.state(!rootContexts.isEmpty(), "No root application context located");
Assert.state(rootContexts.size() == 1, "No unique root application context located");
return rootContexts.get(0);
}
}
}
|
ContextLoaderHook
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java
|
{
"start": 3423,
"end": 8643
}
|
class ____ {
private static final Configuration conf = new Configuration();
private static final Logger LOG =
LoggerFactory.getLogger(TestDelegationTokensWithHA.class);
private static MiniDFSCluster cluster;
private static NameNode nn0;
private static NameNode nn1;
private static FileSystem fs;
private static DelegationTokenSecretManager dtSecretManager;
private static DistributedFileSystem dfs;
private volatile boolean catchup = false;
@BeforeEach
public void setupCluster() throws Exception {
SecurityUtilTestHelper.setTokenServiceUseIp(true);
conf.setBoolean(
DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true);
conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTH_TO_LOCAL,
"RULE:[2:$1@$0](JobTracker@.*FOO.COM)s/@.*//" + "DEFAULT");
cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleHATopology())
.numDataNodes(0)
.build();
cluster.waitActive();
String logicalName = HATestUtil.getLogicalHostname(cluster);
HATestUtil.setFailoverConfigurations(cluster, conf, logicalName, null, 0);
nn0 = cluster.getNameNode(0);
nn1 = cluster.getNameNode(1);
fs = HATestUtil.configureFailoverFs(cluster, conf);
dfs = (DistributedFileSystem)fs;
cluster.transitionToActive(0);
dtSecretManager = NameNodeAdapter.getDtSecretManager(
nn0.getNamesystem());
}
@AfterEach
public void shutdownCluster() throws IOException {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
/**
* Test that, when using ObserverReadProxyProvider with DT authentication,
* the ORPP gracefully handles when the Standby NN throws a StandbyException.
*/
@Test
@Timeout(value = 300)
public void testObserverReadProxyProviderWithDT() throws Exception {
// Make the first node standby, so that the ORPP will try it first
// instead of just using and succeeding on the active
conf.setInt(OBSERVER_PROBE_RETRY_PERIOD_KEY, 0);
cluster.transitionToStandby(0);
cluster.transitionToActive(1);
HATestUtil.setFailoverConfigurations(cluster, conf,
HATestUtil.getLogicalHostname(cluster), 0,
ObserverReadProxyProvider.class);
conf.setBoolean("fs.hdfs.impl.disable.cache", true);
dfs = (DistributedFileSystem) FileSystem.get(conf);
final UserGroupInformation ugi = UserGroupInformation
.createRemoteUser("JobTracker");
final Token<DelegationTokenIdentifier> token =
getDelegationToken(dfs, ugi.getShortUserName());
ugi.addToken(token);
// Recreate the DFS, this time authenticating using a DT
dfs = ugi.doAs((PrivilegedExceptionAction<DistributedFileSystem>)
() -> (DistributedFileSystem) FileSystem.get(conf));
GenericTestUtils.setLogLevel(ObserverReadProxyProvider.LOG, Level.DEBUG);
GenericTestUtils.LogCapturer logCapture = GenericTestUtils.LogCapturer
.captureLogs(ObserverReadProxyProvider.LOG);
try {
dfs.access(new Path("/"), FsAction.READ);
assertTrue(logCapture.getOutput()
.contains("threw StandbyException when fetching HAState"));
HATestUtil.isSentToAnyOfNameNodes(dfs, cluster, 1);
cluster.shutdownNameNode(0);
logCapture.clearOutput();
dfs.access(new Path("/"), FsAction.READ);
assertTrue(logCapture.getOutput().contains("Failed to connect to"));
} finally {
logCapture.stopCapturing();
}
}
@Test
@Timeout(value = 300)
public void testDelegationTokenDFSApi() throws Exception {
final Token<DelegationTokenIdentifier> token =
getDelegationToken(fs, "JobTracker");
DelegationTokenIdentifier identifier = new DelegationTokenIdentifier();
byte[] tokenId = token.getIdentifier();
identifier.readFields(new DataInputStream(
new ByteArrayInputStream(tokenId)));
// Ensure that it's present in the NN's secret manager and can
// be renewed directly from there.
LOG.info("A valid token should have non-null password, " +
"and should be renewed successfully");
assertTrue(null != dtSecretManager.retrievePassword(identifier));
dtSecretManager.renewToken(token, "JobTracker");
// Use the client conf with the failover info present to check
// renewal.
Configuration clientConf = dfs.getConf();
doRenewOrCancel(token, clientConf, TokenTestAction.RENEW);
// Using a configuration that doesn't have the logical nameservice
// configured should result in a reasonable error message.
Configuration emptyConf = new Configuration();
try {
doRenewOrCancel(token, emptyConf, TokenTestAction.RENEW);
fail("Did not throw trying to renew with an empty conf!");
} catch (IOException ioe) {
GenericTestUtils.assertExceptionContains(
"Unable to map logical nameservice URI", ioe);
}
// Ensure that the token can be renewed again after a failover.
cluster.transitionToStandby(0);
cluster.transitionToActive(1);
doRenewOrCancel(token, clientConf, TokenTestAction.RENEW);
doRenewOrCancel(token, clientConf, TokenTestAction.CANCEL);
}
private
|
TestDelegationTokensWithHA
|
java
|
spring-projects__spring-security
|
test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUser.java
|
{
"start": 1003,
"end": 1579
}
|
interface ____ {
/**
* The username to be used. The default is rob
* @return
*/
String username() default "rob";
/**
* The roles to use. The default is "USER". A
* {@link org.springframework.security.core.GrantedAuthority} will be created for each
* value within roles. Each value in roles will automatically be prefixed with
* "ROLE_". For example, the default will result in "ROLE_USER" being used.
* @return
*/
String[] roles() default { "USER" };
/**
* The name of the user
* @return
*/
String name() default "Rob Winch";
}
|
WithMockCustomUser
|
java
|
apache__flink
|
flink-table/flink-table-api-java-bridge/src/test/java/org/apache/flink/table/factories/DataGenTableSourceFactoryTest.java
|
{
"start": 33966,
"end": 34670
}
|
class ____ implements SourceFunction.SourceContext<RowData> {
private final Object lock = new Object();
private final List<RowData> results = new ArrayList<>();
@Override
public void collect(RowData element) {
results.add(element);
}
@Override
public void collectWithTimestamp(RowData element, long timestamp) {}
@Override
public void emitWatermark(Watermark mark) {}
@Override
public void markAsTemporarilyIdle() {}
@Override
public Object getCheckpointLock() {
return lock;
}
@Override
public void close() {}
}
private static
|
TestContext
|
java
|
apache__camel
|
components/camel-microprofile/camel-microprofile-fault-tolerance/src/main/java/org/apache/camel/component/microprofile/faulttolerance/FaultToleranceProcessor.java
|
{
"start": 2752,
"end": 14606
}
|
class ____ extends BaseProcessorSupport
implements CamelContextAware, Navigate<Processor>, org.apache.camel.Traceable, IdAware, RouteIdAware {
private static final Logger LOG = LoggerFactory.getLogger(FaultToleranceProcessor.class);
private CamelContext camelContext;
private String id;
private String routeId;
private final FaultToleranceConfiguration config;
private final Processor processor;
private final Processor fallbackProcessor;
private ExecutorService executorService;
private boolean shutdownExecutorService;
private ProcessorExchangeFactory processorExchangeFactory;
private PooledExchangeTaskFactory taskFactory;
private PooledExchangeTaskFactory fallbackTaskFactory;
private TypedGuard.Builder<Exchange> typedGuardBuilder;
private TypedGuard<Exchange> typedGuard;
public FaultToleranceProcessor(
FaultToleranceConfiguration config,
Processor processor,
Processor fallbackProcessor) {
this.config = config;
this.processor = processor;
this.fallbackProcessor = fallbackProcessor;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getRouteId() {
return routeId;
}
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public TypedGuard<Exchange> getTypedGuard() {
return typedGuard;
}
public void setTypedGuard(TypedGuard<Exchange> typedGuard) {
this.typedGuard = typedGuard;
}
public boolean isShutdownExecutorService() {
return shutdownExecutorService;
}
public void setShutdownExecutorService(boolean shutdownExecutorService) {
this.shutdownExecutorService = shutdownExecutorService;
}
public ExecutorService getExecutorService() {
return executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
@Override
public String getTraceLabel() {
return "faultTolerance";
}
@ManagedAttribute(description = "Returns the current delay in milliseconds.")
public long getDelay() {
return config.getDelay();
}
@ManagedAttribute(description = "Returns the current failure rate in percentage.")
public float getFailureRate() {
return config.getFailureRatio();
}
@ManagedAttribute(description = "Returns the current request volume threshold.")
public int getRequestVolumeThreshold() {
return config.getRequestVolumeThreshold();
}
@ManagedAttribute(description = "Returns the current success threshold.")
public int getSuccessThreshold() {
return config.getSuccessThreshold();
}
@ManagedAttribute(description = "Is timeout enabled")
public boolean isTimeoutEnabled() {
return config.isTimeoutEnabled();
}
@ManagedAttribute(description = "The timeout wait duration")
public long getTimeoutDuration() {
return config.getTimeoutDuration();
}
@ManagedAttribute(description = "The timeout pool size for the thread pool")
public int getTimeoutPoolSize() {
return config.getTimeoutPoolSize();
}
@ManagedAttribute(description = "Is bulkhead enabled")
public boolean isBulkheadEnabled() {
return config.isBulkheadEnabled();
}
@ManagedAttribute(description = "The max amount of concurrent calls the bulkhead will support.")
public int getBulkheadMaxConcurrentCalls() {
return config.getBulkheadMaxConcurrentCalls();
}
@ManagedAttribute(description = "The task queue size for holding waiting tasks to be processed by the bulkhead")
public int getBulkheadWaitingTaskQueue() {
return config.getBulkheadWaitingTaskQueue();
}
@ManagedAttribute(description = "Returns the current state of the circuit breaker")
public String getCircuitBreakerState() {
try {
CircuitBreakerState circuitBreakerState = CircuitBreakerMaintenance.get().currentState(id);
return circuitBreakerState.name();
} catch (Exception e) {
return null;
}
}
@Override
public List<Processor> next() {
if (!hasNext()) {
return null;
}
List<Processor> answer = new ArrayList<>();
answer.add(processor);
if (fallbackProcessor != null) {
answer.add(fallbackProcessor);
}
return answer;
}
@Override
public boolean hasNext() {
return true;
}
@Override
@SuppressWarnings("unchecked")
public boolean process(Exchange exchange, AsyncCallback callback) {
// run this as if we run inside try / catch so there is no regular Camel error handler
exchange.setProperty(ExchangePropertyKey.TRY_ROUTE_BLOCK, true);
CircuitBreakerTask task = (CircuitBreakerTask) taskFactory.acquire(exchange, callback);
CircuitBreakerFallbackTask fallbackTask = null;
try {
// Run the fault-tolerant task within the guard
try {
typedGuard.call(task);
} catch (Exception e) {
// Do fallback if applicable. Note that a fallback handler is not configured on the TypedGuard builder
// and is instead invoked manually here since we need access to the message exchange on each FaultToleranceProcessor.process call
if (fallbackProcessor != null) {
fallbackTask = (CircuitBreakerFallbackTask) fallbackTaskFactory.acquire(exchange, null);
fallbackTask.call();
} else {
throw e;
}
}
} catch (CircuitBreakerOpenException e) {
// the circuit breaker triggered a call rejected
exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false);
exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false);
exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true);
exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true);
} catch (Exception e) {
// some other kind of exception
exchange.setException(e);
} finally {
if (task != null) {
taskFactory.release(task);
}
if (fallbackTask != null) {
fallbackTaskFactory.release(fallbackTask);
}
}
exchange.removeProperty(ExchangePropertyKey.TRY_ROUTE_BLOCK);
callback.done(true);
return true;
}
@Override
protected void doBuild() throws Exception {
ObjectHelper.notNull(camelContext, "CamelContext", this);
boolean pooled = camelContext.getCamelContextExtension().getExchangeFactory().isPooled();
if (pooled) {
int capacity = camelContext.getCamelContextExtension().getExchangeFactory().getCapacity();
taskFactory = new PooledTaskFactory(getId()) {
@Override
public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
return new CircuitBreakerTask();
}
};
taskFactory.setCapacity(capacity);
fallbackTaskFactory = new PooledTaskFactory(getId()) {
@Override
public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
return new CircuitBreakerFallbackTask();
}
};
fallbackTaskFactory.setCapacity(capacity);
} else {
taskFactory = new PrototypeTaskFactory() {
@Override
public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
return new CircuitBreakerTask();
}
};
fallbackTaskFactory = new PrototypeTaskFactory() {
@Override
public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
return new CircuitBreakerFallbackTask();
}
};
}
// create a per processor exchange factory
this.processorExchangeFactory = getCamelContext().getCamelContextExtension()
.getProcessorExchangeFactory().newProcessorExchangeFactory(this);
this.processorExchangeFactory.setRouteId(getRouteId());
this.processorExchangeFactory.setId(getId());
ServiceHelper.buildService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
}
@Override
@SuppressWarnings("unchecked")
protected void doInit() throws Exception {
ObjectHelper.notNull(camelContext, "CamelContext", this);
ServiceHelper.initService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
if (typedGuard == null) {
typedGuardBuilder = TypedGuard.create(Exchange.class)
.withThreadOffload(true)
.withCircuitBreaker()
.name(id)
.delay(config.getDelay(), ChronoUnit.MILLIS)
.failureRatio(config.getFailureRatio())
.requestVolumeThreshold(config.getRequestVolumeThreshold())
.successThreshold(config.getSuccessThreshold())
.done();
if (config.isTimeoutEnabled()) {
typedGuardBuilder.withTimeout()
.duration(config.getTimeoutDuration(), ChronoUnit.MILLIS)
.done();
}
if (config.isBulkheadEnabled()) {
typedGuardBuilder.withBulkhead()
.queueSize(config.getBulkheadWaitingTaskQueue())
.limit(config.getBulkheadMaxConcurrentCalls())
.done();
}
}
}
@Override
protected void doStart() throws Exception {
if (typedGuard == null) {
if (executorService == null) {
executorService = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this,
"CamelMicroProfileFaultTolerance");
shutdownExecutorService = true;
}
typedGuardBuilder.withThreadOffloadExecutor(executorService);
typedGuard = typedGuardBuilder.build();
}
ServiceHelper.startService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
}
@Override
protected void doStop() throws Exception {
if (shutdownExecutorService && executorService != null) {
getCamelContext().getExecutorServiceManager().shutdownNow(executorService);
executorService = null;
}
ServiceHelper.stopService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
try {
CircuitBreakerMaintenance.get().reset(id);
} catch (Exception e) {
// Ignored - CircuitBreaker does not exist
}
}
@Override
protected void doShutdown() throws Exception {
ServiceHelper.stopAndShutdownServices(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
}
private final
|
FaultToleranceProcessor
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/odps/ast/OdpsCreateTableStatement.java
|
{
"start": 1150,
"end": 2683
}
|
class ____ extends HiveCreateTableStatement {
protected SQLAliasedExpr autoPartitionedBy;
protected final List<SQLExpr> withSerdeproperties = new ArrayList<SQLExpr>();
public OdpsCreateTableStatement() {
super(DbType.odps);
}
public SQLExprTableSource getLike() {
return like;
}
public void setLike(SQLName like) {
this.setLike(new SQLExprTableSource(like));
}
public void setLike(SQLExprTableSource like) {
this.like = like;
}
public SQLAliasedExpr getAutoPartitionedBy() {
return autoPartitionedBy;
}
public void setAutoPartitionedBy(SQLAliasedExpr x) {
if (x != null) {
x.setParent(this);
}
this.autoPartitionedBy = x;
}
public void setAutoPartitionedBy(SQLExpr x, String alias) {
setAutoPartitionedBy(new SQLAliasedExpr(x, alias));
}
@Override
protected void accept0(SQLASTVisitor v) {
if (v instanceof OdpsASTVisitor) {
accept0((OdpsASTVisitor) v);
return;
}
super.accept0(v);
}
protected void accept0(OdpsASTVisitor v) {
if (v.visit(this)) {
acceptChild(v);
}
v.endVisit(this);
}
protected void acceptChild(SQLASTVisitor v) {
super.acceptChild(v);
acceptChild(v, withSerdeproperties);
acceptChild(v, storedBy);
}
public List<SQLExpr> getWithSerdeproperties() {
return withSerdeproperties;
}
}
|
OdpsCreateTableStatement
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/JobInitializationMetricsTest.java
|
{
"start": 1177,
"end": 6409
}
|
class ____ {
@Test
public void testBuildingJobInitializationMetricsFromSingleSubtask() {
final ExecutionAttemptID executionAttemptID = ExecutionAttemptID.randomId();
JobInitializationMetricsBuilder initializationMetricsBuilder =
new JobInitializationMetricsBuilder(Collections.singleton(executionAttemptID), 0);
assertThat(initializationMetricsBuilder.isComplete()).isFalse();
SubTaskInitializationMetricsBuilder subTaskInitializationMetricsBuilder =
new SubTaskInitializationMetricsBuilder(0);
subTaskInitializationMetricsBuilder.addDurationMetric("A", 5);
subTaskInitializationMetricsBuilder.addDurationMetric("A", 10);
subTaskInitializationMetricsBuilder.addDurationMetric("B", 20);
SubTaskInitializationMetrics subTaskInitializationMetrics =
subTaskInitializationMetricsBuilder
.setStatus(InitializationStatus.COMPLETED)
.build();
initializationMetricsBuilder.reportInitializationMetrics(
executionAttemptID, subTaskInitializationMetrics);
assertThat(initializationMetricsBuilder.isComplete()).isTrue();
JobInitializationMetrics jobInitializationMetrics = initializationMetricsBuilder.build();
assertThat(jobInitializationMetrics.getStartTs()).isEqualTo(0);
assertThat(jobInitializationMetrics.getEndTs())
.isEqualTo(subTaskInitializationMetrics.getEndTs());
assertThat(jobInitializationMetrics.getStatus()).isEqualTo(InitializationStatus.COMPLETED);
assertThat(jobInitializationMetrics.getDurationMetrics())
.containsOnlyKeys("A", "B")
.containsEntry("A", new SumMaxDuration("A").addDuration(15))
.containsEntry("B", new SumMaxDuration("B").addDuration(20));
}
@Test
public void testBuildingJobInitializationMetricsFromMultipleSubtasks() {
final ExecutionAttemptID firstId = ExecutionAttemptID.randomId();
final ExecutionAttemptID secondId = ExecutionAttemptID.randomId();
final ExecutionAttemptID thirdId = ExecutionAttemptID.randomId();
JobInitializationMetricsBuilder initializationMetricsBuilder =
new JobInitializationMetricsBuilder(
new HashSet<>(Arrays.asList(firstId, secondId, thirdId)), 0);
assertThat(initializationMetricsBuilder.isComplete()).isFalse();
SubTaskInitializationMetricsBuilder subTaskInitializationMetricsBuilder1 =
new SubTaskInitializationMetricsBuilder(0);
subTaskInitializationMetricsBuilder1.addDurationMetric("A", 5);
subTaskInitializationMetricsBuilder1.addDurationMetric("B", 5);
initializationMetricsBuilder.reportInitializationMetrics(
firstId,
subTaskInitializationMetricsBuilder1
.setStatus(InitializationStatus.COMPLETED)
.build(35));
assertThat(initializationMetricsBuilder.isComplete()).isFalse();
SubTaskInitializationMetricsBuilder subTaskInitializationMetricsBuilder =
new SubTaskInitializationMetricsBuilder(100);
subTaskInitializationMetricsBuilder.addDurationMetric("A", 1);
subTaskInitializationMetricsBuilder.addDurationMetric("B", 10);
initializationMetricsBuilder.reportInitializationMetrics(
secondId,
subTaskInitializationMetricsBuilder
.setStatus(InitializationStatus.COMPLETED)
.build(140));
assertThat(initializationMetricsBuilder.isComplete()).isFalse();
initializationMetricsBuilder.reportInitializationMetrics(
thirdId,
new SubTaskInitializationMetricsBuilder(200)
.setStatus(InitializationStatus.FAILED)
.build(1000));
assertThat(initializationMetricsBuilder.isComplete()).isTrue();
JobInitializationMetrics jobInitializationMetrics = initializationMetricsBuilder.build();
assertThat(jobInitializationMetrics.getStartTs()).isEqualTo(0);
assertThat(jobInitializationMetrics.getEndTs()).isEqualTo(1000);
assertThat(jobInitializationMetrics.getStatus()).isEqualTo(InitializationStatus.FAILED);
assertThat(jobInitializationMetrics.getDurationMetrics())
.containsOnlyKeys("A", "B")
.containsEntry("A", new SumMaxDuration("A").addDuration(5).addDuration(1))
.containsEntry("B", new SumMaxDuration("B").addDuration(5).addDuration(10));
}
@Test
public void testSumMaxDuration() throws Exception {
SumMaxDuration duration = new SumMaxDuration("A");
duration.addDuration(1);
assertThat(duration.getSum()).isEqualTo(1);
assertThat(duration.getMax()).isEqualTo(1);
duration.addDuration(5);
assertThat(duration.getSum()).isEqualTo(6);
assertThat(duration.getMax()).isEqualTo(5);
duration.addDuration(4);
assertThat(duration.getSum()).isEqualTo(10);
assertThat(duration.getMax()).isEqualTo(5);
}
}
|
JobInitializationMetricsTest
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/pool/ha/selector/RandomDataSourceSelectorSingleDataSourceTest.java
|
{
"start": 463,
"end": 3978
}
|
class ____ {
private static final Log LOG = LogFactory
.getLog(RandomDataSourceSelectorSingleDataSourceTest.class);
private HighAvailableDataSource highAvailableDataSource;
@Before
public void setUp() throws Exception {
highAvailableDataSource = new HighAvailableDataSource();
String file = "/com/alibaba/druid/pool/ha/ha-with-prefix-datasource.properties";
highAvailableDataSource.setDataSourceFile(file);
highAvailableDataSource.setPropertyPrefix("prefix3");
highAvailableDataSource.setMaxActive(2);
highAvailableDataSource.setMaxWait(500);
highAvailableDataSource.setInitialSize(2);
initSelector(highAvailableDataSource);
highAvailableDataSource.init();
}
@After
public void tearDown() {
highAvailableDataSource.destroy();
highAvailableDataSource = null;
}
@Test
public void testGetWhileBlacklistIsEmpty() {
RandomDataSourceSelector selector = (RandomDataSourceSelector) highAvailableDataSource.getDataSourceSelector();
DruidDataSource dataSource = (DruidDataSource) highAvailableDataSource.getAvailableDataSourceMap()
.get("prefix3.foo");
assertNotNull(selector.get());
assertFalse(dataSource.isTestOnReturn());
}
@Test
public void testGetWhileBlacklisted() throws Exception {
RandomDataSourceSelector selector = (RandomDataSourceSelector) highAvailableDataSource.getDataSourceSelector();
DruidDataSource dataSource = (DruidDataSource) highAvailableDataSource.getAvailableDataSourceMap()
.get("prefix3.foo");
dataSource.setValidationQuery("select xxx from yyy");
Thread.sleep(10 * 1000);
assertTrue(dataSource.isTestOnReturn());
for (int i = 0; i < 5; i++) {
assertNotNull(selector.get());
Thread.sleep(1000);
}
}
@Test
public void testGetAfterRecovering() throws Exception {
RandomDataSourceSelector selector = (RandomDataSourceSelector) highAvailableDataSource.getDataSourceSelector();
DruidDataSource dataSource = (DruidDataSource) highAvailableDataSource.getAvailableDataSourceMap()
.get("prefix3.foo");
dataSource.setValidationQuery("select xxx from yyy");
Thread.sleep(10 * 1000);
assertTrue(dataSource.isTestOnReturn());
assertNotNull(selector.get());
Thread.sleep(10 * 1000);
assertTrue(dataSource.getPoolingCount() == 0);
dataSource.setValidationQuery("values current_timestamp");
Thread.sleep(10 * 1000);
assertFalse(dataSource.isTestOnReturn());
assertNotNull(selector.get());
assertTrue(dataSource.getPoolingCount() > 0);
}
private RandomDataSourceSelector initSelector(HighAvailableDataSource dataSource) {
RandomDataSourceSelector selector = new RandomDataSourceSelector(dataSource);
RandomDataSourceValidateThread validateThread = new RandomDataSourceValidateThread(selector);
RandomDataSourceRecoverThread recoverThread = new RandomDataSourceRecoverThread(selector);
validateThread.setCheckingIntervalSeconds(3);
recoverThread.setRecoverIntervalSeconds(3);
selector.setValidateThread(validateThread);
selector.setRecoverThread(recoverThread);
selector.init();
dataSource.setDataSourceSelector(selector);
return selector;
}
}
|
RandomDataSourceSelectorSingleDataSourceTest
|
java
|
apache__kafka
|
trogdor/src/main/java/org/apache/kafka/trogdor/coordinator/TaskManager.java
|
{
"start": 18483,
"end": 19970
}
|
class ____ implements Callable<Void> {
private final String id;
DestroyTask(String id) {
this.id = id;
}
@Override
public Void call() throws Exception {
if (id.isEmpty()) {
throw new InvalidRequestException("Invalid empty ID in destroyTask request.");
}
ManagedTask task = tasks.remove(id);
if (task == null) {
log.info("Can't destroy task {}: no such task found.", id);
return null;
}
log.info("Destroying task {}.", id);
task.clearStartFuture();
for (Map.Entry<String, Long> entry : task.workerIds.entrySet()) {
long workerId = entry.getValue();
workerStates.remove(workerId);
String nodeName = entry.getKey();
nodeManagers.get(nodeName).destroyWorker(workerId);
}
return null;
}
}
/**
* Update the state of a particular agent's worker.
*
* @param nodeName The node where the agent is running.
* @param workerId The worker ID.
* @param state The worker state.
*/
public void updateWorkerState(String nodeName, long workerId, WorkerState state) {
executor.submit(new UpdateWorkerState(nodeName, workerId, state));
}
/**
* Updates the state of a worker. Process by the state change thread.
*/
|
DestroyTask
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/ArgumentAware.java
|
{
"start": 916,
"end": 1191
}
|
interface ____ {
/**
* Callback hook for nested spring:argument tags to pass their value
* to the parent tag.
* @param argument the result of the nested {@code spring:argument} tag
*/
void addArgument(@Nullable Object argument) throws JspTagException;
}
|
ArgumentAware
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.