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 | processing__processing4 | java/src/processing/mode/java/preproc/PreprocessorResult.java | {
"start": 3566,
"end": 5835
} | class ____ the sketch.
* @param newImportStatements The imports required for the sketch including defaults and core imports.
* @param newEdits The edits made during preprocessing.
* @param newSketchWidth The width of the sketch in pixels or special value like displayWidth;
* @param newSketchHeight The height of the sketch in pixels or special value like displayWidth;
* @param newSketchRenderer The renderer of the sketch.
*/
public PreprocessorResult(PdePreprocessor.Mode newProgramType, int newHeaderOffset,
String newClassName, List<ImportStatement> newImportStatements,
List<TextTransform.Edit> newEdits, String newSketchWidth, String newSketchHeight, String newSketchRenderer,
List<PdePreprocessIssue> newPreprocessIssues) {
if (newClassName == null) {
throw new RuntimeException("Could not find main class");
}
headerOffset = newHeaderOffset;
className = newClassName;
importStatements = newImportStatements;
programType = newProgramType;
edits = newEdits;
preprocessIssues = newPreprocessIssues;
sketchWidth = newSketchWidth;
sketchHeight = newSketchHeight;
sketchRenderer = newSketchRenderer;
}
/**
* Private constructor allowing creation of result indicating preprocess issues.
*
* @param newPreprocessIssues The list of preprocess issues encountered.
*/
private PreprocessorResult(List<PdePreprocessIssue> newPreprocessIssues) {
preprocessIssues = Collections.unmodifiableList(newPreprocessIssues);
headerOffset = 0;
className = "unknown";
programType = PdePreprocessor.Mode.STATIC;
edits = new ArrayList<>();
importStatements = new ArrayList<>();
sketchWidth = null;
sketchHeight = null;
sketchRenderer = null;
}
/**
* Get the list of preprocess issues encountered.
*
* @return List of preprocess issues encountered.
*/
public List<PdePreprocessIssue> getPreprocessIssues() {
return preprocessIssues;
}
/**
* Get the end point of the header.
*
* @return The offset (in number of lines) from the start of the program at which the header
* finishes.
*/
public int getHeaderOffset() {
return headerOffset;
}
/**
* Get the name of the Java | containing |
java | quarkusio__quarkus | independent-projects/bootstrap/maven-resolver/src/test/java/io/quarkus/bootstrap/resolver/maven/test/BootstrapMavenOptionsTest.java | {
"start": 360,
"end": 5660
} | class ____ {
@Test
public void testOffline() throws Exception {
assertTrue(parseOptions("clean install -o -X").hasOption(BootstrapMavenOptions.OFFLINE));
}
@Test
public void testUserSettings() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -o -s custom/settings/file.xml");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.ALTERNATE_USER_SETTINGS));
assertEquals("custom/settings/file.xml", parseOptions.getOptionValue(BootstrapMavenOptions.ALTERNATE_USER_SETTINGS));
}
@Test
public void testGlobalSettings() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -o -gs custom/settings/file.xml");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.ALTERNATE_GLOBAL_SETTINGS));
assertEquals("custom/settings/file.xml", parseOptions.getOptionValue(BootstrapMavenOptions.ALTERNATE_GLOBAL_SETTINGS));
}
@Test
public void testAlternatePomFile() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -o -f alternate/pom-file.xml");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.ALTERNATE_POM_FILE));
assertEquals("alternate/pom-file.xml", parseOptions.getOptionValue(BootstrapMavenOptions.ALTERNATE_POM_FILE));
}
@Test
public void testSupressSnapshotUpdates() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -nsu");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.SUPRESS_SNAPSHOT_UPDATES));
}
@Test
public void testUpdateSnapshots() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -U");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.UPDATE_SNAPSHOTS));
}
@Test
public void testChecksumFailurePolicy() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -C");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.CHECKSUM_FAILURE_POLICY));
}
@Test
public void testChecksumWarningPolicy() throws Exception {
final BootstrapMavenOptions parseOptions = parseOptions("clean install -c");
assertTrue(parseOptions.hasOption(BootstrapMavenOptions.CHECKSUM_WARNING_POLICY));
}
@Test
public void testBatchMode() {
assertEquals("" + CLIManager.BATCH_MODE, BootstrapMavenOptions.BATCH_MODE);
assertTrue(parseOptions("clean install -B").hasOption(BootstrapMavenOptions.BATCH_MODE));
assertTrue(parseOptions("clean install --batch-mode").hasOption(BootstrapMavenOptions.BATCH_MODE));
}
@Test
public void testNoTransferProgress() {
assertEquals(CLIManager.NO_TRANSFER_PROGRESS, BootstrapMavenOptions.NO_TRANSFER_PROGRESS);
assertTrue(parseOptions("clean install -ntp").hasOption(BootstrapMavenOptions.NO_TRANSFER_PROGRESS));
assertTrue(parseOptions("clean install --no-transfer-progress").hasOption(BootstrapMavenOptions.NO_TRANSFER_PROGRESS));
}
@Test
public void testSystemPropertiesWithWhitespaces() throws Exception {
try (AutoCloseable whiteSpace = setProperty("white.space", " value with spaces ");
AutoCloseable nested = setProperty("nested", " -Dnested=other ");
AutoCloseable noValue = setProperty("no-value", "");
AutoCloseable mix = setProperty("quarkus.args", "get abc -u foo --password foo-bar")) {
final BootstrapMavenOptions parseOptions = parseOptions("package " + whiteSpace + nested + noValue + " " + mix);
final Properties userProps = parseOptions.getSystemProperties();
assertEquals(" value with spaces ", userProps.getProperty("white.space"));
assertEquals(" -Dnested=other ", userProps.getProperty("nested"));
assertEquals("", userProps.getProperty("no-value"));
assertEquals("get abc -u foo --password foo-bar", userProps.getProperty("quarkus.args"));
assertEquals(4, userProps.size());
}
}
private BootstrapMavenOptions parseOptions(String line) {
return BootstrapMavenOptions.newInstance(line);
}
private static AutoCloseable setProperty(String name, String value) {
return new AutoCloseable() {
final boolean clear;
final String original;
{
clear = !System.getProperties().containsKey(name);
original = System.setProperty(name, value);
}
@Override
public void close() throws Exception {
if (clear) {
System.clearProperty(name);
} else {
System.setProperty(name, original);
}
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("-D").append(name);
if (value != null && !value.isEmpty()) {
buf.append('=');
buf.append(value);
}
return buf.toString();
}
};
}
}
| BootstrapMavenOptionsTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionEmbeddableElementConversionTest.java | {
"start": 1171,
"end": 1854
} | class ____ {
@BeforeEach
void setUp(SessionFactoryScope scope) {
final ProductEntity entity = new ProductEntity( 1 );
entity.prices = Collections.singletonList( new ProductPrice( new MyBigDecimal( 100.0 ) ) );
scope.fromTransaction( session -> {
session.persist( entity );
return entity.productId;
} );
}
@Test
void testNoClassCastExceptionThrown(SessionFactoryScope scope) {
scope.inTransaction( session -> session.get(
ProductEntity.class,
1
) );
}
@AfterEach
void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Entity(name = "ProductEntity")
static | CollectionEmbeddableElementConversionTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/athena/parser/AthenaCreateTableParser.java | {
"start": 823,
"end": 5620
} | class ____ extends PrestoCreateTableParser {
public AthenaCreateTableParser(SQLExprParser exprParser) {
super(exprParser);
}
@Override
protected void createTableBefore(SQLCreateTableStatement stmt) {
acceptIdentifier(FnvHash.Constants.EXTERNAL);
stmt.setExternal(true);
}
@Override
protected void parseCreateTableRest(SQLCreateTableStatement stmt) {
if (lexer.token() == Token.COMMENT) {
lexer.nextToken();
SQLExpr comment = this.exprParser.expr();
stmt.setComment(comment);
}
if (lexer.nextIf(Token.PARTITIONED)) {
accept(Token.BY);
accept(Token.LPAREN);
for (; ; ) {
if (lexer.token() != Token.IDENTIFIER) {
throw new ParserException("expect identifier. " + lexer.info());
}
SQLColumnDefinition column = this.exprParser.parseColumn();
stmt.addPartitionColumn(column);
if (lexer.isKeepComments() && lexer.hasComment()) {
column.addAfterComment(lexer.readAndResetComments());
}
if (lexer.token() != Token.COMMA) {
break;
} else {
lexer.nextToken();
if (lexer.isKeepComments() && lexer.hasComment()) {
column.addAfterComment(lexer.readAndResetComments());
}
}
}
accept(Token.RPAREN);
}
if (lexer.nextIfIdentifier(FnvHash.Constants.CLUSTERED)) {
accept(Token.BY);
accept(Token.LPAREN);
for (; ; ) {
SQLSelectOrderByItem item = this.exprParser.parseSelectOrderByItem();
stmt.addClusteredByItem(item);
if (lexer.token() == Token.COMMA) {
lexer.nextToken();
continue;
}
break;
}
accept(Token.RPAREN);
}
if (lexer.token() == Token.ROW
|| lexer.identifierEquals(FnvHash.Constants.ROW)) {
parseRowFormat(stmt);
}
if (lexer.identifierEquals(FnvHash.Constants.STORED)) {
lexer.nextToken();
accept(Token.AS);
if (lexer.identifierEquals(FnvHash.Constants.INPUTFORMAT)) {
HiveInputOutputFormat format = new HiveInputOutputFormat();
lexer.nextToken();
format.setInput(this.exprParser.primary());
if (lexer.identifierEquals(FnvHash.Constants.OUTPUTFORMAT)) {
lexer.nextToken();
format.setOutput(this.exprParser.primary());
}
stmt.setStoredAs(format);
} else {
SQLName name = this.exprParser.name();
stmt.setStoredAs(name);
}
}
parseCreateTableWithSerderPropertie(stmt);
if (lexer.identifierEquals(FnvHash.Constants.LOCATION)) {
lexer.nextToken();
SQLExpr location = this.exprParser.primary();
stmt.setLocation(location);
}
if (lexer.identifierEquals(FnvHash.Constants.TBLPROPERTIES)) {
lexer.nextToken();
accept(Token.LPAREN);
parseAssignItems(stmt.getTableOptions(), stmt, false);
accept(Token.RPAREN);
}
}
protected void parseRowFormat(SQLCreateTableStatement stmt) {
SQLExternalRecordFormat format = this.getExprParser().parseRowFormat();
stmt.setRowFormat(format);
}
protected void parseCreateTableWithSerderPropertie(SQLCreateTableStatement stmt) {
if (stmt instanceof AthenaCreateTableStatement) {
AthenaCreateTableStatement athenaStmt = (AthenaCreateTableStatement) stmt;
if (lexer.token() == Token.WITH) {
lexer.nextToken();
acceptIdentifier("SERDEPROPERTIES");
accept(Token.LPAREN);
for (; ; ) {
String key = lexer.stringVal();
lexer.nextToken();
accept(Token.EQ);
SQLExpr value = this.exprParser.primary();
athenaStmt.getSerdeProperties().put(key, value);
if (lexer.token() == Token.COMMA) {
lexer.nextToken();
continue;
}
break;
}
accept(Token.RPAREN);
}
}
}
@Override
protected AthenaCreateTableStatement newCreateStatement() {
return new AthenaCreateTableStatement();
}
}
| AthenaCreateTableParser |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/nestedbeans/TestData.java | {
"start": 225,
"end": 649
} | class ____ {
private TestData() {
}
public static User createUser() {
return new User( "John", new Car( "Chrysler", 1955, Arrays.asList(
new Wheel().front().left(),
new Wheel().front().right(),
new Wheel().rear().left(),
new Wheel().rear().right()
) ),
new House( "Black", 1834, new Roof( 1, RoofType.BOX ) )
);
}
}
| TestData |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfiguration.java | {
"start": 1459,
"end": 2438
} | class ____ configuration that can be automatically applied by
* Spring Boot. Auto-configuration classes are regular
* {@link Configuration @Configuration} with the exception that
* {@link Configuration#proxyBeanMethods() proxyBeanMethods} is always {@code false}. They
* are located using {@link ImportCandidates}.
* <p>
* Generally, auto-configuration classes are top-level classes that are marked as
* {@link Conditional @Conditional} (most often using
* {@link ConditionalOnClass @ConditionalOnClass} and
* {@link ConditionalOnMissingBean @ConditionalOnMissingBean} annotations).
*
* @author Moritz Halbritter
* @see EnableAutoConfiguration
* @see AutoConfigureBefore
* @see AutoConfigureAfter
* @see Conditional
* @see ConditionalOnClass
* @see ConditionalOnMissingBean
* @since 2.7.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore
@AutoConfigureAfter
public @ | provides |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/OutputCommitter.java | {
"start": 11834,
"end": 12236
} | interface ____ calling the old method. Note
* that the input types are different between the new and old apis and this
* is a bridge between the two.
*/
@Override
public final
void setupTask(org.apache.hadoop.mapreduce.TaskAttemptContext taskContext
) throws IOException {
setupTask((TaskAttemptContext) taskContext);
}
/**
* This method implements the new | by |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/tokenizers/MPNetTokenizer.java | {
"start": 806,
"end": 2635
} | class ____ extends BertTokenizer {
public static final String UNKNOWN_TOKEN = "[UNK]";
public static final String SEPARATOR_TOKEN = "</s>";
public static final String PAD_TOKEN = "<pad>";
public static final String CLASS_TOKEN = "<s>";
public static final String MASK_TOKEN = MPNetTokenization.MASK_TOKEN;
private static final Set<String> NEVER_SPLIT = Set.of(MASK_TOKEN);
protected MPNetTokenizer(
List<String> originalVocab,
SortedMap<String, Integer> vocab,
boolean doLowerCase,
boolean doTokenizeCjKChars,
boolean doStripAccents,
boolean withSpecialTokens,
int maxSequenceLength,
Set<String> neverSplit
) {
super(
originalVocab,
vocab,
doLowerCase,
doTokenizeCjKChars,
doStripAccents,
withSpecialTokens,
maxSequenceLength,
Sets.union(neverSplit, NEVER_SPLIT),
SEPARATOR_TOKEN,
CLASS_TOKEN,
PAD_TOKEN,
MASK_TOKEN,
UNKNOWN_TOKEN
);
}
@Override
protected int getNumExtraTokensForSeqPair() {
return 4;
}
TokenizationResult.TokensBuilder createTokensBuilder(int clsTokenId, int sepTokenId, boolean withSpecialTokens) {
return new MPNetTokenizationResult.MPNetTokensBuilder(withSpecialTokens, clsTokenId, sepTokenId);
}
@Override
public TokenizationResult buildTokenizationResult(List<TokenizationResult.Tokens> tokenizations) {
return new MPNetTokenizationResult(originalVocab, tokenizations, getPadTokenId().orElseThrow());
}
public static Builder mpBuilder(List<String> vocab, Tokenization tokenization) {
return new Builder(vocab, tokenization);
}
public static | MPNetTokenizer |
java | elastic__elasticsearch | build-tools/src/main/java/org/elasticsearch/gradle/testclusters/TestClusterInfo.java | {
"start": 568,
"end": 1254
} | class ____ {
private final List<String> allHttpSocketURI;
private final List<String> allTransportPortURI;
private final List<File> auditLogs;
public TestClusterInfo(List<String> allHttpSocketURI, List<String> allTransportPortURI, List<File> auditLogs) {
this.allHttpSocketURI = allHttpSocketURI;
this.allTransportPortURI = allTransportPortURI;
this.auditLogs = auditLogs;
}
public List<String> getAllHttpSocketURI() {
return allHttpSocketURI;
}
public List<String> getAllTransportPortURI() {
return allTransportPortURI;
}
public List<File> getAuditLogs() {
return auditLogs;
}
}
| TestClusterInfo |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/CustomNonBlockingReturnTypeTest.java | {
"start": 3898,
"end": 4187
} | class ____ implements HasMessage {
private final String message;
public CustomType(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
public static | CustomType |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ClassInitializationDeadlockTest.java | {
"start": 8459,
"end": 8892
} | class ____ extends A {}
""")
.doTest();
}
@Test
public void negativeAutoValueExtension() {
testHelper
.addSourceLines(
"$$AutoValue_Foo.java",
"""
class $$AutoValue_Foo extends Foo {}
""")
.addSourceLines(
"A.java",
"""
import com.google.auto.value.AutoValue;
@AutoValue
abstract | B |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/internals/SessionKeySchema.java | {
"start": 1308,
"end": 8412
} | class ____ implements SegmentedBytesStore.KeySchema {
private static final int SUFFIX_SIZE = 2 * TIMESTAMP_SIZE;
private static final byte[] MIN_SUFFIX = new byte[SUFFIX_SIZE];
public static int keyByteLength(final Bytes key) {
return (key == null ? 0 : key.get().length) + 2 * TIMESTAMP_SIZE;
}
@Override
public Bytes upperRangeFixedSize(final Bytes key, final long to) {
final Windowed<Bytes> sessionKey = upperRangeFixedWindow(key, to);
return SessionKeySchema.toBinary(sessionKey);
}
public static <K> Windowed<K> upperRangeFixedWindow(final K key, final long to) {
return new Windowed<K>(key, new SessionWindow(to, Long.MAX_VALUE));
}
@Override
public Bytes lowerRangeFixedSize(final Bytes key, final long from) {
final Windowed<Bytes> sessionKey = lowerRangeFixedWindow(key, from);
return SessionKeySchema.toBinary(sessionKey);
}
public static <K> Windowed<K> lowerRangeFixedWindow(final K key, final long from) {
return new Windowed<K>(key, new SessionWindow(0, Math.max(0, from)));
}
@Override
public Bytes upperRange(final Bytes key, final long to) {
if (key == null) {
return null;
}
final byte[] maxSuffix = ByteBuffer.allocate(SUFFIX_SIZE)
// the end timestamp can be as large as possible as long as it's larger than start time
.putLong(Long.MAX_VALUE)
// this is the start timestamp
.putLong(to)
.array();
return OrderedBytes.upperRange(key, maxSuffix);
}
@Override
public Bytes lowerRange(final Bytes key, final long from) {
if (key == null) {
return null;
}
return OrderedBytes.lowerRange(key, MIN_SUFFIX);
}
@Override
public long segmentTimestamp(final Bytes key) {
return SessionKeySchema.extractEndTimestamp(key.get());
}
@Override
public HasNextCondition hasNextCondition(final Bytes binaryKeyFrom, final Bytes binaryKeyTo, final long from, final long to, final boolean forward) {
return iterator -> {
while (iterator.hasNext()) {
final Bytes bytes = iterator.peekNextKey();
final Windowed<Bytes> windowedKey = SessionKeySchema.from(bytes);
if ((binaryKeyFrom == null || windowedKey.key().compareTo(binaryKeyFrom) >= 0)
&& (binaryKeyTo == null || windowedKey.key().compareTo(binaryKeyTo) <= 0)
&& windowedKey.window().end() >= from
&& windowedKey.window().start() <= to) {
return true;
}
iterator.next();
}
return false;
};
}
@Override
public <S extends Segment> List<S> segmentsToSearch(final Segments<S> segments,
final long from,
final long to,
final boolean forward) {
return segments.segments(from, Long.MAX_VALUE, forward);
}
private static <K> K extractKey(final byte[] binaryKey,
final Deserializer<K> deserializer,
final String topic) {
return deserializer.deserialize(topic, extractKeyBytes(binaryKey));
}
static byte[] extractKeyBytes(final byte[] binaryKey) {
final byte[] bytes = new byte[binaryKey.length - 2 * TIMESTAMP_SIZE];
System.arraycopy(binaryKey, 0, bytes, 0, bytes.length);
return bytes;
}
static long extractEndTimestamp(final byte[] binaryKey) {
return ByteBuffer.wrap(binaryKey).getLong(binaryKey.length - 2 * TIMESTAMP_SIZE);
}
static long extractStartTimestamp(final byte[] binaryKey) {
return ByteBuffer.wrap(binaryKey).getLong(binaryKey.length - TIMESTAMP_SIZE);
}
static Window extractWindow(final byte[] binaryKey) {
final ByteBuffer buffer = ByteBuffer.wrap(binaryKey);
final long start = buffer.getLong(binaryKey.length - TIMESTAMP_SIZE);
final long end = buffer.getLong(binaryKey.length - 2 * TIMESTAMP_SIZE);
return new SessionWindow(start, end);
}
public static <K> Windowed<K> from(final byte[] binaryKey,
final Deserializer<K> keyDeserializer,
final String topic) {
final K key = extractKey(binaryKey, keyDeserializer, topic);
final Window window = extractWindow(binaryKey);
return new Windowed<>(key, window);
}
public static Windowed<Bytes> from(final Bytes bytesKey) {
final byte[] binaryKey = bytesKey.get();
final Window window = extractWindow(binaryKey);
return new Windowed<>(Bytes.wrap(extractKeyBytes(binaryKey)), window);
}
public static <K> Windowed<K> from(final Windowed<Bytes> keyBytes,
final Deserializer<K> keyDeserializer,
final String topic) {
final K key = keyDeserializer.deserialize(topic, keyBytes.key().get());
return new Windowed<>(key, keyBytes.window());
}
public static <K> byte[] toBinary(final Windowed<K> sessionKey,
final Serializer<K> serializer,
final String topic) {
final byte[] bytes = serializer.serialize(topic, sessionKey.key());
return toBinary(Bytes.wrap(bytes), sessionKey.window().start(), sessionKey.window().end()).get();
}
public static Bytes toBinary(final Windowed<Bytes> sessionKey) {
return toBinary(sessionKey.key(), sessionKey.window().start(), sessionKey.window().end());
}
public static Bytes toBinary(final Bytes key,
final long startTime,
final long endTime) {
final ByteBuffer buf = ByteBuffer.allocate(keyByteLength(key));
writeBinary(buf, key, startTime, endTime);
return Bytes.wrap(buf.array());
}
public static void writeBinary(final ByteBuffer buf, final Windowed<Bytes> sessionKey) {
writeBinary(buf, sessionKey.key(), sessionKey.window().start(), sessionKey.window().end());
}
public static void writeBinary(final ByteBuffer buf,
final Bytes key,
final long startTime,
final long endTime) {
// we search for the session window that can overlap with the [ESET, LSST] range
// since the session window length can vary, we define the search boundary as:
// lower: [0, ESET]
// upper: [LSST, INF]
// and by putting the end time first and then the start time, the serialized search boundary
// is: [(ESET-0), (INF-LSST)]
buf.put(key.get());
buf.putLong(endTime);
buf.putLong(startTime);
}
}
| SessionKeySchema |
java | apache__camel | components/camel-aws/camel-aws2-cw/src/test/java/org/apache/camel/component/aws2/cw/integration/CwComponentIT.java | {
"start": 1208,
"end": 2200
} | class ____ extends Aws2CwBase {
@EndpointInject("mock:result")
private MockEndpoint mock;
@Test
public void sendInOnly() throws Exception {
mock.expectedMessageCount(1);
template.send("direct:start", ExchangePattern.InOnly, new Processor() {
public void process(Exchange exchange) {
exchange.getIn().setHeader(Cw2Constants.METRIC_NAME, "ExchangesCompleted");
exchange.getIn().setHeader(Cw2Constants.METRIC_VALUE, "2.0");
exchange.getIn().setHeader(Cw2Constants.METRIC_UNIT, "Count");
}
});
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("aws2-cw://http://camel.apache.org/aws-cw")
.to("mock:result");
}
};
}
}
| CwComponentIT |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueJava8Test.java | {
"start": 33083,
"end": 33365
} | class ____<@Nullable T> {
abstract @Nullable T thing();
static <@Nullable T> Builder<T> builder() {
return new AutoValue_AutoValueJava8Test_AnnotatedTypeParameterWithBuilder.Builder<T>();
}
@AutoValue.Builder
abstract static | AnnotatedTypeParameterWithBuilder |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdWithIgnoreUnknownTest.java | {
"start": 569,
"end": 1311
} | class ____ {
private String type;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type",
defaultImpl = Default2611.class
)
private Default2611 data;
@JsonCreator
public Wrapper2611(
@JsonProperty(value = "type", required = true) String type,
@JsonProperty(value = "data", required = true) Default2611 data
) {
this.type = type;
this.data = data;
}
String getType() {
return type;
}
Default2611 getData() {
return data;
}
}
static | Wrapper2611 |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/testFixtures/java/org/springframework/boot/web/server/servlet/AbstractServletWebServerFactoryTests.java | {
"start": 71521,
"end": 72026
} | class ____ implements InputStreamFactory {
private final AtomicBoolean requested = new AtomicBoolean();
@Override
public InputStream create(InputStream in) throws IOException {
if (this.requested.get()) {
throw new IllegalStateException("On deflated InputStream already requested");
}
this.requested.set(true);
return new GZIPInputStream(in);
}
boolean wasCompressionUsed() {
return this.requested.get();
}
}
@SuppressWarnings("serial")
static | TestGzipInputStreamFactory |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/FileSystemTimelineWriterImpl.java | {
"start": 9677,
"end": 11670
} | class ____<T> {
abstract T run() throws IOException;
T runWithRetries() throws IOException, InterruptedException {
int retry = 0;
while (true) {
try {
return run();
} catch (IOException e) {
LOG.info("Exception while executing a FS operation.", e);
if (++retry > fsNumRetries) {
LOG.info("Maxed out FS retries. Giving up!");
throw e;
}
LOG.info("Will retry operation on FS. Retry no. {}" +
" after sleeping for {} seconds", retry, fsRetryInterval);
Thread.sleep(fsRetryInterval);
}
}
}
}
private boolean createFile(Path newFile) throws IOException {
return fs.createNewFile(newFile);
}
/**
* In order to make this writeInternal atomic as a part of writeInternal
* we will first writeInternal data to .tmp file and then rename it.
* Here we are assuming that rename is atomic for underlying file system.
*
* @param outputPath outputPath.
* @param data data.
* @throws IOException Signals that an I/O exception of some sort has occurred.
*/
protected void writeFile(Path outputPath, byte[] data) throws IOException {
Path tempPath =
new Path(outputPath.getParent(), outputPath.getName() + ".tmp");
FSDataOutputStream fsOut = null;
// This file will be overwritten when app/attempt finishes for saving the
// final status.
try {
fsOut = fs.create(tempPath, true);
FSDataInputStream fsIn = fs.open(outputPath);
IOUtils.copyBytes(fsIn, fsOut, config, false);
fsIn.close();
fs.delete(outputPath, false);
fsOut.write(data);
fsOut.close();
fs.rename(tempPath, outputPath);
} catch (IOException ie) {
LOG.error("Got an exception while writing file", ie);
}
}
// specifically escape the separator character
private static String escape(String str) {
return str.replace(File.separatorChar, '_');
}
}
| FSAction |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/AdviceWithRoutePolicyTest.java | {
"start": 2952,
"end": 3172
} | class ____ extends RoutePolicySupport {
@Override
public void onExchangeBegin(Route route, Exchange exchange) {
exchange.getIn().setHeader("MyRoutePolicy", true);
}
}
}
| MyRoutePolicy |
java | quarkusio__quarkus | extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/RequestScopedSessionHolder.java | {
"start": 333,
"end": 770
} | class ____ {
private final Map<String, Session> sessions = new HashMap<>();
public Session getOrCreateSession(String name, SessionFactory factory) {
return sessions.computeIfAbsent(name, (n) -> factory.openSession());
}
@PreDestroy
public void destroy() {
for (Map.Entry<String, Session> entry : sessions.entrySet()) {
entry.getValue().close();
}
}
}
| RequestScopedSessionHolder |
java | apache__maven | impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnenc/EncryptParser.java | {
"start": 1001,
"end": 1401
} | class ____ extends BaseParser {
@Override
protected Options parseCliOptions(LocalContext context) {
try {
return CommonsCliEncryptOptions.parse(context.parserRequest.args().toArray(new String[0]));
} catch (ParseException e) {
throw new IllegalArgumentException("Failed to parse command line options: " + e.getMessage(), e);
}
}
}
| EncryptParser |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfAssertionTest.java | {
"start": 7316,
"end": 7619
} | class ____ {
void test(int x) {
// BUG: Diagnostic contains: fail
assertNotEquals(x, x);
// BUG: Diagnostic contains: fail
assertNotEquals("foo", x, x);
}
}
""")
.doTest();
}
}
| Test |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalBetweenTest.java | {
"start": 185,
"end": 978
} | class ____ extends TestCase {
public void test_between() throws Exception {
assertEquals(false, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? between 1 and 3", 0));
assertEquals(true, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? between 1 and 3", 2));
assertEquals(false, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? between 1 and 3", 4));
}
public void test_not_between() throws Exception {
assertEquals(true, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? not between 1 and 3", 0));
assertEquals(false, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? not between 1 and 3", 2));
assertEquals(true, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? not between 1 and 3", 4));
}
}
| EvalBetweenTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest73.java | {
"start": 1022,
"end": 2487
} | class ____ extends MysqlTest {
@Test
public void test_one() throws Exception {
String sql = "CREATE TABLE total ("
+ " id INT NOT NULL AUTO_INCREMENT,"
+ " message CHAR(20), INDEX(a))"
+ " ENGINE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement stmt = parser.parseCreateTable();
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
Column column = visitor.getColumn("total", "id");
assertNotNull(column);
assertEquals("INT", column.getDataType());
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE total ("
+ "\n\tid INT NOT NULL AUTO_INCREMENT,"
+ "\n\tmessage CHAR(20),"
+ "\n\tINDEX(a)"
+ "\n) ENGINE = MERGE UNION = (t1, t2) INSERT_METHOD = LAST", output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("create table total ("
+ "\n\tid INT not null auto_increment,"
+ "\n\tmessage CHAR(20),"
+ "\n\tindex(a)"
+ "\n) engine = MERGE union = (t1, t2) insert_method = LAST", output);
}
}
}
| MySqlCreateTableTest73 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e3/b3/PolicyId.java | {
"start": 286,
"end": 398
} | class ____ implements Serializable {
@Column(name="`type`", length=32)
String type;
DependentId depPK;
}
| PolicyId |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/output/VectorMetadataParser.java | {
"start": 868,
"end": 6959
} | class ____ implements ComplexDataParser<VectorMetadata> {
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(VectorMetadataParser.class);
public static final VectorMetadataParser INSTANCE = new VectorMetadataParser();
// Field names in the VINFO response
private static final String ATTRIBUTES_COUNT = "attributes-count";
private static final String SIZE = "size";
private static final String MAX_NODES = "hnsw-m";
private static final String VSET_UID = "vset-uid";
private static final String QUANT_TYPE = "quant-type";
private static final String MAX_LEVEL = "max-level";
private static final String VECTOR_DIM = "vector-dim";
private static final String MAX_NODE_UID = "hnsw-max-node-uid";
private static final String PROJECTION_INPUT_DIM = "projection-input-dim";
// Quant types
private static final String INT8 = "int8";
private static final String FLOAT32 = "float32";
private static final String BINARY = "binary";
/**
* Utility constructor.
*/
private VectorMetadataParser() {
}
/**
* Parse the output of the Redis VINFO command and convert it to a {@link VectorMetadata} object.
* <p>
* The VINFO command returns an array of key-value pairs, where each pair consists of a field name followed by its value.
* This method extracts the relevant fields and populates a {@link VectorMetadata} object with the corresponding values.
*
* @param dynamicData output of VINFO command
* @return a {@link VectorMetadata} instance containing the parsed information
* @throws IllegalArgumentException if the input data is null, empty, or has an invalid format
*/
@Override
public VectorMetadata parse(ComplexData dynamicData) {
List<Object> data = verifyStructure(dynamicData);
if (data == null) {
// Valid response for the case when a vector set does not exist
return null;
}
VectorMetadata metadata = new VectorMetadata();
// Parse the array of key-value pairs
for (int i = 0; i < data.size(); i += 2) {
if (i + 1 >= data.size()) {
break; // Avoid index out of bounds
}
String key = data.get(i).toString();
Object value = data.get(i + 1);
switch (key) {
case ATTRIBUTES_COUNT:
metadata.setAttributesCount(parseInteger(value));
break;
case SIZE:
metadata.setSize(parseInteger(value));
break;
case QUANT_TYPE:
metadata.setType(parseQuantizationType(value.toString()));
break;
case VECTOR_DIM:
metadata.setDimensionality(parseInteger(value));
break;
case MAX_LEVEL:
metadata.setMaxLevel(parseInteger(value));
break;
case MAX_NODES:
metadata.setMaxNodes(parseInteger(value));
break;
case MAX_NODE_UID:
metadata.setMaxNodeUid(parseInteger(value));
break;
case PROJECTION_INPUT_DIM:
metadata.setProjectionInputDim(parseInteger(value));
break;
case VSET_UID:
metadata.setvSetUid(parseInteger(value));
break;
}
}
return metadata;
}
/**
* Verifies that the input data has the expected structure for a VINFO command response.
*
* @param vinfoOutput the output from the VINFO command
* @return the list of key-value pairs from the VINFO command
* @throws IllegalArgumentException if the input data is null, empty, or has an invalid format
*/
private List<Object> verifyStructure(ComplexData vinfoOutput) {
if (vinfoOutput == null) {
LOG.warn("Failed while parsing VINFO: vinfoOutput must not be null");
return null;
}
List<Object> data;
try {
data = vinfoOutput.getDynamicList();
} catch (UnsupportedOperationException e) {
try {
Map<Object, Object> map = vinfoOutput.getDynamicMap();
data = new ArrayList<>(map.size() * 2);
for (Map.Entry<Object, Object> entry : map.entrySet()) {
data.add(entry.getKey());
data.add(entry.getValue());
}
} catch (UnsupportedOperationException ex) {
LOG.warn("Failed while parsing VINFO: vinfoOutput must be a list or a map", ex);
return new ArrayList<>();
}
}
if (data == null || data.isEmpty()) {
LOG.warn("Failed while parsing VINFO: data must not be null or empty");
return new ArrayList<>();
}
// VINFO returns an array of key-value pairs, so the size must be even
if (data.size() % 2 != 0) {
LOG.warn("Failed while parsing VINFO: data must contain key-value pairs");
return new ArrayList<>();
}
return data;
}
/**
* Parses a value from the VINFO response into an Integer.
*
* @param value the value to parse
* @return the parsed Integer value, or null if the value cannot be parsed
*/
private Integer parseInteger(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
// Return null if the string cannot be parsed as an integer
return null;
}
}
return null;
}
/**
* Maps a quantization type string from the VINFO response to a {@link QuantizationType} | VectorMetadataParser |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/GcTimeMonitor.java | {
"start": 8668,
"end": 10481
} | class ____ implements Cloneable {
private long timestamp;
private long gcMonitorRunTime, totalGcTime, totalGcCount;
private int gcTimePercentage;
/**
* Returns the absolute timestamp when this measurement was taken.
* @return timestamp.
*/
public long getTimestamp() {
return timestamp;
}
/**
* Returns the time since the start of the associated GcTimeMonitor.
* @return GcMonitorRunTime.
*/
public long getGcMonitorRunTime() {
return gcMonitorRunTime;
}
/**
* Returns accumulated GC time since this JVM started.
* @return AccumulatedGcTime.
*/
public long getAccumulatedGcTime() {
return totalGcTime;
}
/**
* Returns the accumulated number of GC pauses since this JVM started.
* @return AccumulatedGcCount.
*/
public long getAccumulatedGcCount() {
return totalGcCount;
}
/**
* Returns the percentage (0..100) of time that the JVM spent in GC pauses
* within the observation window of the associated GcTimeMonitor.
*
* @return GcTimePercentage.
*/
public int getGcTimePercentage() {
return gcTimePercentage;
}
private synchronized void update(long inTimestamp, long inGcMonitorRunTime,
long inTotalGcTime, long inTotalGcCount, int inGcTimePercentage) {
this.timestamp = inTimestamp;
this.gcMonitorRunTime = inGcMonitorRunTime;
this.totalGcTime = inTotalGcTime;
this.totalGcCount = inTotalGcCount;
this.gcTimePercentage = inGcTimePercentage;
}
@Override
public synchronized GcData clone() {
try {
return (GcData) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
private static | GcData |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/BulkDeleteUtils.java | {
"start": 1002,
"end": 1053
} | class ____ bulk delete operations.
*/
public final | for |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/plugins/PluginsServiceTests.java | {
"start": 38780,
"end": 38951
} | class ____ implements TestExtensionPoint {
public BadSingleParameterConstructorExtension(String bad) {}
}
public static | BadSingleParameterConstructorExtension |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/stat/PerfTest.java | {
"start": 827,
"end": 1181
} | class ____ {
private volatile long value;
static final AtomicLongFieldUpdater<A> updater = AtomicLongFieldUpdater.newUpdater(A.class, "value");
public long incrementAndGet() {
return updater.incrementAndGet(this);
}
public long getValue() {
return value;
}
}
public static | A |
java | dropwizard__dropwizard | dropwizard-core/src/main/java/io/dropwizard/core/cli/ConfiguredCommand.java | {
"start": 1083,
"end": 5475
} | class ____<T extends Configuration> extends Command {
private boolean asynchronous;
@Nullable
private T configuration;
protected ConfiguredCommand(String name, String description) {
super(name, description);
this.asynchronous = false;
}
/**
* Returns the {@link Class} of the configuration type.
*
* @return the {@link Class} of the configuration type
*/
protected Class<T> getConfigurationClass() {
return Generics.getTypeParameter(getClass(), Configuration.class);
}
/**
* Returns the parsed configuration or {@code null} if it hasn't been parsed yet.
*
* @return Returns the parsed configuration or {@code null} if it hasn't been parsed yet
* @since 2.0.19
*/
@Nullable
public T getConfiguration() {
return configuration;
}
/**
* Configure the command's {@link Subparser}. <p><strong> N.B.: if you override this method, you
* <em>must</em> call {@code super.override(subparser)} in order to preserve the configuration
* file parameter in the subparser. </strong></p>
*
* @param subparser the {@link Subparser} specific to the command
*/
@Override
public void configure(Subparser subparser) {
addFileArgument(subparser);
}
/**
* Adds the configuration file argument for the configured command.
* @param subparser The subparser to register the argument on
* @return the register argument
*/
protected Argument addFileArgument(Subparser subparser) {
return subparser.addArgument("file")
.nargs("?")
.help("application configuration file");
}
@Override
@SuppressWarnings("unchecked")
public void run(Bootstrap<?> wildcardBootstrap, Namespace namespace) throws Exception {
final Bootstrap<T> bootstrap = (Bootstrap<T>) wildcardBootstrap;
configuration = parseConfiguration(bootstrap.getConfigurationFactoryFactory(),
bootstrap.getConfigurationSourceProvider(),
bootstrap.getValidatorFactory().getValidator(),
namespace.getString("file"),
getConfigurationClass(),
bootstrap.getObjectMapper());
try {
if (configuration != null) {
configuration.getLoggingFactory().configure(bootstrap.getMetricRegistry(),
bootstrap.getApplication().getName());
}
run(bootstrap, namespace, configuration);
} finally {
if (!asynchronous) {
cleanup();
} else if (configuration != null) {
configuration.getLoggingFactory().stop();
}
}
}
protected void cleanupAsynchronously() {
this.asynchronous = true;
}
protected void cleanup() {
if (configuration != null) {
configuration.getLoggingFactory().stop();
}
}
/**
* Runs the command with the given {@link Bootstrap} and {@link Configuration}.
*
* @param bootstrap the bootstrap
* @param namespace the parsed command line namespace
* @param configuration the configuration object
* @throws Exception if something goes wrong
*/
protected abstract void run(Bootstrap<T> bootstrap,
Namespace namespace,
T configuration) throws Exception;
private T parseConfiguration(ConfigurationFactoryFactory<T> configurationFactoryFactory,
ConfigurationSourceProvider provider,
Validator validator,
String path,
Class<T> klass,
ObjectMapper objectMapper) throws IOException, ConfigurationException {
final ConfigurationFactory<T> configurationFactory = configurationFactoryFactory
.create(klass, validator, objectMapper, "dw");
if (path != null) {
return configurationFactory.build(provider, path);
}
return configurationFactory.build();
}
}
| ConfiguredCommand |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/MessageFramer.java | {
"start": 14078,
"end": 15844
} | class ____ extends OutputStream {
private static final int FIRST_BUFFER_SIZE = 4096;
private final List<WritableBuffer> bufferList = new ArrayList<>();
private WritableBuffer current;
/**
* This is slow, don't call it. If you care about write overhead, use a BufferedOutputStream.
* Better yet, you can use your own single byte buffer and call
* {@link #write(byte[], int, int)}.
*/
@Override
public void write(int b) {
if (current != null && current.writableBytes() > 0) {
current.write((byte)b);
return;
}
byte[] singleByte = new byte[]{(byte)b};
write(singleByte, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
if (current == null) {
// Request len bytes initially from the allocator, it may give us more.
current = bufferAllocator.allocate(Math.max(FIRST_BUFFER_SIZE, len));
bufferList.add(current);
}
while (len > 0) {
int canWrite = Math.min(len, current.writableBytes());
if (canWrite == 0) {
// Assume message is twice as large as previous assumption if were still not done,
// the allocator may allocate more or less than this amount.
int needed = Math.max(len, current.readableBytes() * 2);
current = bufferAllocator.allocate(needed);
bufferList.add(current);
} else {
current.write(b, off, canWrite);
off += canWrite;
len -= canWrite;
}
}
}
private int readableBytes() {
int readable = 0;
for (WritableBuffer writableBuffer : bufferList) {
readable += writableBuffer.readableBytes();
}
return readable;
}
}
}
| BufferChainOutputStream |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java | {
"start": 3848,
"end": 5515
} | class ____<T> extends AutowiredElementResolver implements InstanceSupplier<T> {
private final ExecutableLookup lookup;
private final @Nullable ThrowingFunction<RegisteredBean, T> generatorWithoutArguments;
private final @Nullable ThrowingBiFunction<RegisteredBean, AutowiredArguments, T> generatorWithArguments;
private final String @Nullable [] shortcutBeanNames;
private BeanInstanceSupplier(ExecutableLookup lookup,
@Nullable ThrowingFunction<RegisteredBean, T> generatorWithoutArguments,
@Nullable ThrowingBiFunction<RegisteredBean, AutowiredArguments, T> generatorWithArguments,
String @Nullable [] shortcutBeanNames) {
this.lookup = lookup;
this.generatorWithoutArguments = generatorWithoutArguments;
this.generatorWithArguments = generatorWithArguments;
this.shortcutBeanNames = shortcutBeanNames;
}
/**
* Create a {@link BeanInstanceSupplier} that resolves
* arguments for the specified bean constructor.
* @param <T> the type of instance supplied
* @param parameterTypes the constructor parameter types
* @return a new {@link BeanInstanceSupplier} instance
*/
public static <T> BeanInstanceSupplier<T> forConstructor(Class<?>... parameterTypes) {
Assert.notNull(parameterTypes, "'parameterTypes' must not be null");
Assert.noNullElements(parameterTypes, "'parameterTypes' must not contain null elements");
return new BeanInstanceSupplier<>(new ConstructorLookup(parameterTypes), null, null, null);
}
/**
* Create a new {@link BeanInstanceSupplier} that
* resolves arguments for the specified factory method.
* @param <T> the type of instance supplied
* @param declaringClass the | BeanInstanceSupplier |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/SerializationUtils.java | {
"start": 509,
"end": 1051
} | class ____ {
public static Object deserialize(byte[] bytes) throws Exception {
try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
return in.readObject();
}
}
public static byte[] serialize(Object object) throws Exception {
try (var byteArrayOutputStream = new ByteArrayOutputStream();
var objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
return byteArrayOutputStream.toByteArray();
}
}
}
| SerializationUtils |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThat_with_LongStream_Test.java | {
"start": 983,
"end": 4164
} | class ____ {
private final LongStream longStream = LongStream.empty();
@Test
void should_create_Assert() {
Object assertions = assertThat(LongStream.of(823952L, 1947230585L));
assertThat(assertions).isNotNull();
}
@Test
void should_assert_on_size() {
assertThat(LongStream.empty()).isEmpty();
assertThat(LongStream.of(123L, 5674L, 363L)).isNotEmpty()
.hasSize(3);
}
@Test
void isEqualTo_should_honor_comparing_the_same_mocked_stream() {
LongStream stream = mock();
assertThat(stream).isEqualTo(stream);
}
@Test
void stream_can_be_asserted_twice() {
LongStream names = LongStream.of(823952L, 1947230585L);
assertThat(names).containsExactly(823952L, 1947230585L)
.containsExactly(823952L, 1947230585L);
}
@Test
void should_not_consume_stream_when_asserting_non_null() {
LongStream stream = mock();
assertThat(stream).isNotNull();
verifyNoInteractions(stream);
}
@Test
void isInstanceOf_should_check_the_original_stream_without_consuming_it() {
LongStream stream = mock();
assertThat(stream).isInstanceOf(LongStream.class);
verifyNoInteractions(stream);
}
@Test
void isInstanceOfAny_should_check_the_original_stream_without_consuming_it() {
LongStream stream = mock();
assertThat(stream).isInstanceOfAny(LongStream.class, String.class);
verifyNoInteractions(stream);
}
@Test
void isOfAnyClassIn_should_check_the_original_stream_without_consuming_it() {
LongStream stream = mock();
assertThat(stream).isOfAnyClassIn(Double.class, stream.getClass());
}
@Test
void isExactlyInstanceOf_should_check_the_original_stream() {
// factory creates use internal classes
assertThat(longStream).isExactlyInstanceOf(longStream.getClass());
}
@Test
void isNotExactlyInstanceOf_should_check_the_original_stream() {
assertThat(longStream).isNotExactlyInstanceOf(LongStream.class);
Throwable error = catchThrowable(() -> assertThat(longStream).isNotExactlyInstanceOf(longStream.getClass()));
assertThat(error).isInstanceOf(AssertionError.class);
}
@Test
void isNotInstanceOf_should_check_the_original_stream() {
assertThat(longStream).isNotInstanceOf(Long.class);
}
@Test
void isNotInstanceOfAny_should_check_the_original_stream() {
assertThat(longStream).isNotInstanceOfAny(Long.class, String.class);
}
@Test
void isNotOfAnyClassIn_should_check_the_original_stream() {
assertThat(longStream).isNotOfAnyClassIn(Long.class, String.class);
}
@Test
void isSameAs_should_check_the_original_stream_without_consuming_it() {
LongStream stream = mock();
assertThat(stream).isSameAs(stream);
verifyNoInteractions(stream);
}
@Test
void isNotSameAs_should_check_the_original_stream_without_consuming_it() {
LongStream stream = mock();
try {
assertThat(stream).isNotSameAs(stream);
} catch (AssertionError e) {
verifyNoInteractions(stream);
return;
}
Assertions.fail("Expected assertionError, because assert notSame on same stream.");
}
}
| Assertions_assertThat_with_LongStream_Test |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/support/ClassPathXmlApplicationContext.java | {
"start": 5727,
"end": 5969
} | class ____ resources relative to a
* given Class. For full flexibility, consider using a GenericApplicationContext
* with an XmlBeanDefinitionReader and a ClassPathResource argument.
* @param path relative (or absolute) path within the | path |
java | apache__flink | flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlAddPartitions.java | {
"start": 3514,
"end": 3684
} | class ____ {
public boolean ifNotExists;
public List<SqlNodeList> partSpecs;
public List<SqlNodeList> partProps;
}
}
| AlterTableAddPartitionContext |
java | apache__camel | dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/AutoConfigureDownloadListener.java | {
"start": 1367,
"end": 4864
} | class ____ implements DownloadListener, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(AutoConfigureDownloadListener.class);
private CamelContext camelContext;
private final Set<String> artifacts = new HashSet<>();
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public void onDownloadDependency(String groupId, String artifactId, String version) {
// noop
}
@Override
public void onDownloadedDependency(String groupId, String artifactId, String version) {
if (!artifacts.contains(artifactId)) {
artifacts.add(artifactId);
autoConfigureDependencies(artifactId);
autoConfigure(artifactId);
}
}
@Override
public void onAlreadyDownloadedDependency(String groupId, String artifactId, String version) {
// noop
}
protected void autoConfigureDependencies(String artifactId) {
// the auto-configuration may require additional dependencies being downloaded first
InputStream is = getClass().getResourceAsStream("/auto-configure/" + artifactId + ".properties");
if (is != null) {
try {
String script = IOHelper.loadText(is);
for (String line : script.split("\n")) {
line = line.trim();
if (line.startsWith("dependency=")) {
MavenGav gav = MavenGav.parseGav(line.substring(11));
DependencyDownloader downloader = getCamelContext().hasService(DependencyDownloader.class);
// these are extra dependencies used in special use-case so download as hidden
downloader.downloadHiddenDependency(gav.getGroupId(), gav.getArtifactId(), gav.getVersion());
}
}
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeException(e);
} finally {
IOHelper.close(is);
}
}
}
protected void autoConfigure(String artifactId) {
// is there any special auto configuration scripts?
InputStream is = getClass().getResourceAsStream("/auto-configure/" + artifactId + ".java");
if (is != null) {
try {
// ensure java-joor is downloaded
DependencyDownloader downloader = getCamelContext().hasService(DependencyDownloader.class);
// these are extra dependencies used in special use-case so download as hidden
downloader.downloadHiddenDependency("org.apache.camel", "camel-joor", camelContext.getVersion());
// execute script via java-joor
String script = IOHelper.loadText(is);
Language lan = camelContext.resolveLanguage("java");
Expression exp = lan.createExpression(script);
Object out = exp.evaluate(new DefaultExchange(camelContext), Object.class);
if (ObjectHelper.isNotEmpty(out)) {
LOG.info("{}", out);
}
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeException(e);
} finally {
IOHelper.close(is);
}
}
}
}
| AutoConfigureDownloadListener |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/floats/Floats_assertIsZero_Test.java | {
"start": 1184,
"end": 2547
} | class ____ extends FloatsBaseTest {
@Test
void should_succeed_since_actual_is_zero() {
floats.assertIsZero(someInfo(), 0.0f);
}
@Test
void should_fail_since_actual_is_not_zero() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsZero(someInfo(), 2.0f))
.withMessage(shouldBeEqualMessage("2.0f", "0.0f"));
}
@Test
void should_fail_since_actual_is_negative_zero_and_not_primitive() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsZero(someInfo(), -0.0f))
.withMessage(shouldBeEqualMessage("-0.0f", "0.0f"));
}
@Test
void should_succeed_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() {
floatsWithAbsValueComparisonStrategy.assertIsZero(someInfo(), 0.0f);
}
@Test
void should_fail_since_actual_is_zero_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floatsWithAbsValueComparisonStrategy.assertIsZero(someInfo(),
2.0f))
.withMessage(shouldBeEqualMessage("2.0f", "0.0f"));
}
}
| Floats_assertIsZero_Test |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/AssertNotEqualsAssertionsTests.java | {
"start": 4963,
"end": 6278
} | class ____ {
@Test
void assertNotEqualsInt() {
int unexpected = 1;
int actual = 2;
assertNotEquals(unexpected, actual);
assertNotEquals(unexpected, actual, "message");
assertNotEquals(unexpected, actual, () -> "message");
}
@Test
void withEqualValues() {
int unexpected = 1;
int actual = 1;
try {
assertNotEquals(unexpected, actual);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: not equal but was: <1>");
}
}
@Test
void withEqualValuesWithMessage() {
int unexpected = 1;
int actual = 1;
try {
assertNotEquals(unexpected, actual, "custom message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "custom message");
assertMessageEndsWith(ex, "expected: not equal but was: <1>");
}
}
@Test
void withEqualValuesWithMessageSupplier() {
int unexpected = 1;
int actual = 1;
try {
assertNotEquals(unexpected, actual, () -> "custom message from supplier");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "custom message from supplier");
assertMessageEndsWith(ex, "expected: not equal but was: <1>");
}
}
}
@Nested
| AssertNotEqualsInt |
java | netty__netty | handler/src/test/java/io/netty/handler/ssl/JdkSslClientContextTest.java | {
"start": 794,
"end": 1190
} | class ____ extends SslContextTest {
@Override
protected SslContext newSslContext(File crtFile, File keyFile, String pass) throws SSLException {
return new JdkSslClientContext(crtFile, InsecureTrustManagerFactory.INSTANCE, crtFile, keyFile, pass,
null, null, IdentityCipherSuiteFilter.INSTANCE, ApplicationProtocolConfig.DISABLED, 0, 0);
}
}
| JdkSslClientContextTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/path/PathAssert_hasExtension_Test.java | {
"start": 785,
"end": 1110
} | class ____ extends PathAssertBaseTest {
@Override
protected PathAssert invoke_api_method() {
return assertions.hasExtension("java");
}
@Override
protected void verify_internal_effects() {
verify(paths).assertHasExtension(getInfo(assertions), getActual(assertions), "java");
}
}
| PathAssert_hasExtension_Test |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java | {
"start": 807,
"end": 1306
} | class ____ {
private SystemProperties() {
}
public static @Nullable String get(String... properties) {
for (String property : properties) {
try {
String override = System.getProperty(property);
override = (override != null) ? override : System.getenv(property);
if (override != null) {
return override;
}
}
catch (Throwable ex) {
System.err.println("Could not resolve '" + property + "' as system property: " + ex);
}
}
return null;
}
}
| SystemProperties |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scheduling/annotation/SchedulingConfigurer.java | {
"start": 1682,
"end": 2075
} | interface ____ {
/**
* Callback allowing a {@link org.springframework.scheduling.TaskScheduler}
* and specific {@link org.springframework.scheduling.config.Task} instances
* to be registered against the given the {@link ScheduledTaskRegistrar}.
* @param taskRegistrar the registrar to be configured
*/
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}
| SchedulingConfigurer |
java | elastic__elasticsearch | modules/repository-gcs/src/main/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageService.java | {
"start": 16003,
"end": 21884
} | interface
____ (ProjectId.DEFAULT.equals(project.id())) {
continue;
}
final ProjectSecrets projectSecrets = project.custom(ProjectSecrets.TYPE);
// Project secrets can be null when node restarts. It may not have any GCS credentials if GCS is not in use.
if (projectSecrets == null
|| projectSecrets.getSettingNames().stream().noneMatch(key -> key.startsWith(GCS_SETTING_PREFIX))) {
// Most likely there won't be any existing client, but attempt to remove it anyway just in case
perProjectClientsHolders.remove(project.id());
continue;
}
final Settings currentSettings = Settings.builder()
// merge with static settings such as max retries etc
// TODO: https://elasticco.atlassian.net/browse/ES-11716 Consider change this to use per-project settings
.put(nodeGcsSettings)
.setSecureSettings(projectSecrets.getSettings())
.build();
final var allClientSettings = GoogleCloudStorageClientSettings.load(currentSettings);
assert allClientSettings.isEmpty() == false;
// Skip project clients that have no credentials configured. This should not happen in serverless.
// But it is safer to skip them and is also a more consistent behaviour with the cases when
// project secrets are not present.
final var clientSettingsWithCredentials = allClientSettings.entrySet()
.stream()
.filter(entry -> entry.getValue().getCredential() != null)
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
// TODO: If performance is an issue, we may consider comparing just the relevant project secrets for new or updated clients
// and avoid building the clientSettings
if (newOrUpdated(project.id(), clientSettingsWithCredentials)) {
if (allClientSettings.size() != clientSettingsWithCredentials.size()) {
logger.warn(
"Project [{}] has [{}] GCS client settings, but [{}] is usable due to missing credentials for clients {}",
project.id(),
allClientSettings.size(),
clientSettingsWithCredentials.size(),
Sets.difference(allClientSettings.keySet(), clientSettingsWithCredentials.keySet())
);
}
updatedPerProjectClients.put(project.id(), new PerProjectClientsHolder(clientSettingsWithCredentials));
}
}
// Updated projects
for (var projectId : updatedPerProjectClients.keySet()) {
assert ProjectId.DEFAULT.equals(projectId) == false;
perProjectClientsHolders.put(projectId, updatedPerProjectClients.get(projectId));
}
// Removed projects
for (var projectId : perProjectClientsHolders.keySet()) {
if (currentProjects.containsKey(projectId) == false) {
assert ProjectId.DEFAULT.equals(projectId) == false;
perProjectClientsHolders.remove(projectId);
}
}
}
void refreshAndClearCacheForClusterClients(Map<String, GoogleCloudStorageClientSettings> clientsSettings) {
clusterClientsHolder.refreshAndClearCache(clientsSettings);
}
MeteredStorage client(ProjectId projectId, String clientName, String repositoryName, GcsRepositoryStatsCollector statsCollector)
throws IOException {
if (projectId == null || ProjectId.DEFAULT.equals(projectId)) {
return clusterClientsHolder.client(clientName, repositoryName, statsCollector);
} else {
return getClientsHolderSafe(projectId).client(clientName, repositoryName, statsCollector);
}
}
void closeRepositoryClients(ProjectId projectId, String repositoryName) {
if (projectId == null || ProjectId.DEFAULT.equals(projectId)) {
clusterClientsHolder.closeRepositoryClients(repositoryName);
} else {
final var old = perProjectClientsHolders.get(projectId);
if (old != null) {
old.closeRepositoryClients(repositoryName);
}
}
}
// package private for tests
ClusterClientsHolder getClusterClientsHolder() {
return clusterClientsHolder;
}
// package private for tests
Map<ProjectId, ClientsHolder> getPerProjectClientsHolders() {
return perProjectClientsHolders == null ? null : Map.copyOf(perProjectClientsHolders);
}
private boolean newOrUpdated(ProjectId projectId, Map<String, GoogleCloudStorageClientSettings> currentClientSettings) {
final var old = perProjectClientsHolders.get(projectId);
if (old == null) {
return true;
}
return currentClientSettings.equals(old.allClientSettings()) == false;
}
private ClientsHolder getClientsHolderSafe(ProjectId projectId) {
assert ProjectId.DEFAULT.equals(projectId) == false;
final var clientsHolder = perProjectClientsHolders.get(projectId);
if (clientsHolder == null) {
throw new IllegalArgumentException("No GCS client is configured for project [" + projectId + "]");
}
return clientsHolder;
}
}
abstract | if |
java | google__dagger | javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java | {
"start": 42220,
"end": 42459
} | class ____");
} else {
subject.hasErrorCount(1);
subject.hasErrorContaining(errorMessage)
.onSource(parentConflictsWithChild)
.onLineContaining(" | ParentModule |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/impl/http2/Http2ServerConnection.java | {
"start": 696,
"end": 1046
} | interface ____ extends HttpServerConnection, Http2Connection {
void sendPush(int streamId,
HostAndPort authority,
HttpMethod method,
MultiMap headers,
String path,
StreamPriority streamPriority,
Promise<Http2ServerStream> promise);
}
| Http2ServerConnection |
java | quarkusio__quarkus | extensions/vertx/runtime/src/main/java/io/quarkus/vertx/core/runtime/VertxMDC.java | {
"start": 532,
"end": 10914
} | enum ____ implements MDCProvider {
INSTANCE;
final InheritableThreadLocal<Map<String, Object>> inheritableThreadLocalMap = new InheritableThreadLocal<>() {
@Override
protected Map<String, Object> childValue(Map<String, Object> parentValue) {
if (parentValue == null) {
return null;
}
return new HashMap<>(parentValue);
}
@Override
protected Map<String, Object> initialValue() {
return new HashMap<>();
}
};
/**
* Get the value for a key, or {@code null} if there is no mapping.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @return the value
*/
@Override
public String get(String key) {
return get(key, getContext());
}
/**
* Get the value for a key, or {@code null} if there is no mapping.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @return the value
*/
@Override
public Object getObject(String key) {
return getObject(key, getContext());
}
/**
* Get the value for a key the in specified Context, or {@code null} if there is no mapping.
* If the informed context is null it falls back to the thread local context map.
*
* @param key the key
* @param vertxContext the context
* @return the value
*/
public String get(String key, Context vertxContext) {
Object value = getObject(key, vertxContext);
return value != null ? value.toString() : null;
}
/**
* Get the value for a key the in specified Context, or {@code null} if there is no mapping.
* If the context is null it falls back to the thread local context map.
*
* @param key the key
* @param vertxContext the context
* @return the value
*/
public Object getObject(String key, Context vertxContext) {
Objects.requireNonNull(key);
return contextualDataMap(vertxContext).get(key);
}
/**
* Set the value of a key, returning the old value (if any) or {@code null} if there was none.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @param value the new value
* @return the old value or {@code null} if there was none
*/
@Override
public String put(String key, String value) {
return put(key, value, getContext());
}
/**
* Set the value of a key, returning the old value (if any) or {@code null} if there was none.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @param value the new value
* @return the old value or {@code null} if there was none
*/
@Override
public Object putObject(String key, Object value) {
return putObject(key, value, getContext());
}
/**
* Set the value of a key, returning the old value (if any) or {@code null} if there was none.
* If the informed context is null it falls back to the thread local context map.
*
* @param key the key
* @param value the new value
* @return the old value or {@code null} if there was none
*/
public String put(String key, String value, Context vertxContext) {
Object oldValue = putObject(key, value, vertxContext);
return oldValue != null ? oldValue.toString() : null;
}
/**
* Set the value of a key, returning the old value (if any) or {@code null} if there was none.
* If the informed context is null it falls back to the thread local context map.
*
* @param key the key
* @param value the new value
* @return the old value or {@code null} if there was none
*/
public Object putObject(String key, Object value, Context vertxContext) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
return contextualDataMap(vertxContext).put(key, value);
}
/**
* Removes a key.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @return the old value or {@code null} if there was none
*/
@Override
public String remove(String key) {
return remove(key, getContext());
}
/**
* Removes a key.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @param key the key
* @return the old value or {@code null} if there was none
*/
@Override
public Object removeObject(String key) {
return removeObject(key, getContext());
}
/**
* Removes a key.
* If the informed context is null it falls back to the thread local context map.
*
* @param key the key
* @return the old value or {@code null} if there was none
*/
public String remove(String key, Context vertxContext) {
Object oldValue = removeObject(key, vertxContext);
return oldValue != null ? oldValue.toString() : null;
}
/**
* Removes a key.
* If the informed context is null it falls back to the thread local context map.
*
* @param key the key
* @return the old value or {@code null} if there was none
*/
public Object removeObject(String key, Context vertxContext) {
Objects.requireNonNull(key);
return contextualDataMap(vertxContext).remove(key);
}
/**
* Get a copy of the MDC map. This is a relatively expensive operation.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @return a copy of the map
*/
@Override
public Map<String, String> copy() {
return copy(getContext());
}
/**
* Get a copy of the MDC map. This is a relatively expensive operation.
*
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*
* @return a copy of the map
*/
@Override
public Map<String, Object> copyObject() {
return copyObject(getContext());
}
/**
* Determine whether the current MDC map is empty.
*
* @return {@code true} if there are no bound MDC values, or {@code false} otherwise
*/
public boolean isEmpty() {
return contextualDataMap(getContext()).isEmpty();
}
/**
* Get a copy of the MDC map. This is a relatively expensive operation.
* If the informed context is null it falls back to the thread local context map.
*
* @return a copy of the map
*/
public Map<String, String> copy(Context vertxContext) {
final HashMap<String, String> result = new HashMap<>();
Map<String, Object> contextualDataMap = contextualDataMap(vertxContext);
for (Map.Entry<String, Object> entry : contextualDataMap.entrySet()) {
result.put(entry.getKey(), entry.getValue().toString());
}
return result;
}
/**
* Get a copy of the MDC map. This is a relatively expensive operation.
* If the informed context is null it falls back to the thread local context map.
*
* @return a copy of the map
*/
public Map<String, Object> copyObject(Context vertxContext) {
return new HashMap<>(contextualDataMap(vertxContext));
}
/**
* Clear the current MDC map.
* Tries to use the current Vert.x Context, if the context is non-existent
* meaning that it was called out of a Vert.x thread it will fall back to
* the thread local context map.
*/
@Override
public void clear() {
clear(getContext());
}
/**
* Clear the current MDC map.
* If the informed context is null it falls back to the thread local context map.
*/
public void clear(Context vertxContext) {
contextualDataMap(vertxContext).clear();
}
/**
* Gets the current duplicated context or a new duplicated context if a Vert.x Context exists. Multiple invocations
* of this method may return the same or different context. If the current context is a duplicate one, multiple
* invocations always return the same context. If the current context is not duplicated, a new instance is returned
* with each method invocation.
*
* @return a duplicated Vert.x Context or null.
*/
private Context getContext() {
Context context = Vertx.currentContext();
if (context != null) {
Context dc = getOrCreateDuplicatedContext(context);
setContextSafe(dc, true);
return dc;
}
return null;
}
/**
* Gets the current Contextual Data Map from the current Vert.x Context if it is not null or the default
* ThreadLocal Data Map for use in non Vert.x Threads.
*
* @return the current Contextual Data Map.
*/
@SuppressWarnings({ "unchecked" })
private Map<String, Object> contextualDataMap(Context ctx) {
if (ctx == null) {
return inheritableThreadLocalMap.get();
}
ConcurrentMap<Object, Object> lcd = Objects.requireNonNull((ContextInternal) ctx).localContextData();
return (ConcurrentMap<String, Object>) lcd.computeIfAbsent(VertxMDC.class.getName(),
k -> new ConcurrentHashMap<String, Object>());
}
}
| VertxMDC |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java | {
"start": 39232,
"end": 41976
} | class ____ {
private final Metrics metrics;
SensorCreator(Metrics metrics) {
this.metrics = metrics;
}
private Sensor createSensor(StatType statType, int index) {
Sensor sensor = metrics.sensor("kafka.requests." + index);
Map<String, String> tags = Collections.singletonMap("tag", "tag" + index);
switch (statType) {
case AVG:
sensor.add(metrics.metricName("test.metric.avg", "avg", tags), new Avg());
break;
case TOTAL:
sensor.add(metrics.metricName("test.metric.total", "total", tags), new CumulativeSum());
break;
case COUNT:
sensor.add(metrics.metricName("test.metric.count", "count", tags), new WindowedCount());
break;
case MAX:
sensor.add(metrics.metricName("test.metric.max", "max", tags), new Max());
break;
case MIN:
sensor.add(metrics.metricName("test.metric.min", "min", tags), new Min());
break;
case RATE:
sensor.add(metrics.metricName("test.metric.rate", "rate", tags), new Rate());
break;
case SIMPLE_RATE:
sensor.add(metrics.metricName("test.metric.simpleRate", "simpleRate", tags), new SimpleRate());
break;
case SUM:
sensor.add(metrics.metricName("test.metric.sum", "sum", tags), new WindowedSum());
break;
case VALUE:
sensor.add(metrics.metricName("test.metric.value", "value", tags), new Value());
break;
case PERCENTILES:
sensor.add(metrics.metricName("test.metric.percentiles", "percentiles", tags),
new Percentiles(100, -100, 100, Percentiles.BucketSizing.CONSTANT,
new Percentile(metrics.metricName("test.median", "percentiles"), 50.0),
new Percentile(metrics.metricName("test.perc99_9", "percentiles"), 99.9)));
break;
case METER:
sensor.add(new Meter(metrics.metricName("test.metric.meter.rate", "meter", tags),
metrics.metricName("test.metric.meter.total", "meter", tags)));
break;
default:
throw new IllegalStateException("Invalid stat type " + statType);
}
return sensor;
}
}
}
| SensorCreator |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/api/AggregationFunctionTest.java | {
"start": 22454,
"end": 23156
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
public int f0;
public int f1;
public MyPojo(int f0, int f1) {
this.f0 = f0;
this.f1 = f1;
}
public MyPojo() {}
@Override
public String toString() {
return "POJO(" + f0 + "," + f1 + ")";
}
@Override
public boolean equals(Object other) {
if (other instanceof MyPojo) {
return this.f0 == ((MyPojo) other).f0 && this.f1 == ((MyPojo) other).f1;
} else {
return false;
}
}
}
/** POJO. */
public static | MyPojo |
java | apache__flink | flink-docs/src/main/java/org/apache/flink/docs/rest/RuntimeRestAPIDocGenerator.java | {
"start": 2829,
"end": 3780
} | class ____ {
/**
* Generates the Runtime REST API documentation.
*
* @param args args[0] contains the directory into which the generated files are placed
* @throws IOException if any file operation failed
*/
public static void main(String[] args) throws IOException, ConfigurationException {
String outputDirectory = args[0];
for (final RuntimeRestAPIVersion apiVersion : RuntimeRestAPIVersion.values()) {
if (apiVersion == RuntimeRestAPIVersion.V0) {
// this version exists only for testing purposes
continue;
}
createHtmlFile(
new DocumentingDispatcherRestEndpoint(),
apiVersion,
Paths.get(
outputDirectory,
"rest_" + apiVersion.getURLVersionPrefix() + "_dispatcher.html"));
}
}
}
| RuntimeRestAPIDocGenerator |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conversion/jodatime/Target.java | {
"start": 258,
"end": 1694
} | class ____ {
private String dateTime;
private String localDateTime;
private String localDate;
private String localTime;
private Date dateTimeForDateConversion;
private Calendar dateTimeForCalendarConversion;
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public String getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(String localDateTime) {
this.localDateTime = localDateTime;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalTime() {
return localTime;
}
public void setLocalTime(String localTime) {
this.localTime = localTime;
}
public Date getDateTimeForDateConversion() {
return dateTimeForDateConversion;
}
public void setDateTimeForDateConversion(Date dateTimeForDateConversion) {
this.dateTimeForDateConversion = dateTimeForDateConversion;
}
public Calendar getDateTimeForCalendarConversion() {
return dateTimeForCalendarConversion;
}
public void setDateTimeForCalendarConversion(Calendar dateTimeForCalendarConversion) {
this.dateTimeForCalendarConversion = dateTimeForCalendarConversion;
}
}
| Target |
java | grpc__grpc-java | api/src/main/java/io/grpc/LoadBalancerProvider.java | {
"start": 2861,
"end": 4533
} | class ____ loaded. It
* shouldn't change, and there is no point doing so.
*
* <p>The policy name should consist of only lower case letters letters, underscore and digits,
* and can only start with letters.
*/
public abstract String getPolicyName();
/**
* Parses the config for the Load Balancing policy unpacked from the service config. This will
* return a {@link ConfigOrError} which contains either the successfully parsed config, or the
* {@link Status} representing the failure to parse. Implementations are expected to not throw
* exceptions but return a Status representing the failure. If successful, the load balancing
* policy config should be immutable.
*
* @param rawLoadBalancingPolicyConfig The {@link Map} representation of the load balancing
* policy choice.
* @return a tuple of the fully parsed and validated balancer configuration, else the Status.
* @since 1.20.0
* @see <a href="https://github.com/grpc/proposal/blob/master/A24-lb-policy-config.md">
* A24-lb-policy-config.md</a>
*/
public ConfigOrError parseLoadBalancingPolicyConfig(Map<String, ?> rawLoadBalancingPolicyConfig) {
return UNKNOWN_CONFIG;
}
@Override
public final String toString() {
return MoreObjects.toStringHelper(this)
.add("policy", getPolicyName())
.add("priority", getPriority())
.add("available", isAvailable())
.toString();
}
/**
* Uses identity equality.
*/
@Override
public final boolean equals(Object other) {
return this == other;
}
@Override
public final int hashCode() {
return super.hashCode();
}
private static final | is |
java | dropwizard__dropwizard | dropwizard-logging/src/test/java/io/dropwizard/logging/common/FileAppenderFactoryTest.java | {
"start": 1835,
"end": 20262
} | class ____ {
static {
BootstrapLogging.bootstrap();
}
private final ObjectMapper mapper = Jackson.newObjectMapper();
private final Validator validator = BaseValidator.newValidator();
@Test
void isDiscoverable() {
assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes())
.contains(FileAppenderFactory.class);
}
@Test
void includesCallerData() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.isIncludeCallerData()).isFalse());
fileAppenderFactory.setIncludeCallerData(true);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.isIncludeCallerData()).isTrue());
}
@Test
void isRolling(@TempDir Path tempDir) {
// the method we want to test is protected, so we need to override it so we can see it
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<ILoggingEvent>() {
@Override
public FileAppender<ILoggingEvent> buildAppender(LoggerContext context) {
return super.buildAppender(context);
}
};
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d.log.gz").toString());
assertThat(fileAppenderFactory.buildAppender(new LoggerContext())).isInstanceOf(RollingFileAppender.class);
}
@Test
void testAppenderIsStarted(@TempDir Path tempDir) {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("application.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setArchivedFileCount(20);
fileAppenderFactory.setArchivedLogFilenamePattern("application-%i.log");
fileAppenderFactory.setMaxFileSize(DataSize.megabytes(500));
fileAppenderFactory.setImmediateFlush(false);
fileAppenderFactory.setThreshold("ERROR");
Appender<ILoggingEvent> appender = fileAppenderFactory.build(new LoggerContext(),
"test-app",
new DropwizardLayoutFactory(),
new NullLevelFilterFactory<>(),
new AsyncLoggingEventAppenderFactory());
assertThat(appender.isStarted()).isTrue();
appender.stop();
assertThat(appender.isStarted()).isFalse();
}
@Test
void hasArchivedLogFilenamePattern(@TempDir Path tempDir) {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("must have archivedLogFilenamePattern if archive is true");
fileAppenderFactory.setArchive(false);
errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
void isValidForInfiniteRolledFiles(@TempDir Path tempDir) {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setArchivedFileCount(0);
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d.log.gz").toString());
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
assertThat(fileAppenderFactory.buildAppender(new LoggerContext())).isNotNull();
}
@Test
void isValidForMaxFileSize(@TempDir Path tempDir) {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setMaxFileSize(DataSize.kibibytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d.log.gz").toString());
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("when specifying maxFileSize, archivedLogFilenamePattern must contain %i");
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d-%i.log.gz").toString());
errors = ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
void hasMaxFileSizeValidation(@TempDir Path tempDir) {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%i.log.gz").toString());
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("when archivedLogFilenamePattern contains %i, maxFileSize must be specified");
fileAppenderFactory.setMaxFileSize(DataSize.kibibytes(1));
errors = ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
void testCurrentFileNameErrorWhenArchiveIsNotEnabled() {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("currentLogFilename can only be null when archiving is enabled");
fileAppenderFactory.setCurrentLogFilename("test");
errors = ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
void testCurrentFileNameCanBeNullWhenArchiveIsEnabled() {
FileAppenderFactory<?> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setArchivedLogFilenamePattern("name-to-be-used");
fileAppenderFactory.setCurrentLogFilename(null);
Collection<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
void testCurrentLogFileNameIsEmptyAndAppenderUsesArchivedNameInstead(@TempDir Path tempDir) {
final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>();
appenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("test-archived-name-%d.log").toString());
final FileAppender<ILoggingEvent> rollingAppender = appenderFactory.buildAppender(new LoggerContext());
final String file = rollingAppender.getFile();
assertThat(file).contains("test-archived-name-")
.endsWith(LocalDateTime.now(appenderFactory.getTimeZone().toZoneId()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".log");
}
@Test
void hasMaxFileSize(@TempDir Path tempDir) {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setMaxFileSize(DataSize.kibibytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d-%i.log.gz").toString());
RollingFileAppender<ILoggingEvent> appender = (RollingFileAppender<ILoggingEvent>) fileAppenderFactory.buildAppender(new LoggerContext());
assertThat(appender.getTriggeringPolicy()).isInstanceOf(SizeAndTimeBasedRollingPolicy.class);
assertThat(appender.getRollingPolicy())
.extracting("maxFileSize")
.isInstanceOfSatisfying(FileSize.class, maxFileSize -> assertThat(maxFileSize.getSize()).isEqualTo(1024L));
}
@Test
void hasMaxFileSizeFixedWindow(@TempDir Path tempDir) {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setCurrentLogFilename(tempDir.resolve("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setMaxFileSize(DataSize.kibibytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%i.log.gz").toString());
RollingFileAppender<ILoggingEvent> appender = (RollingFileAppender<ILoggingEvent>) fileAppenderFactory.buildAppender(new LoggerContext());
assertThat(appender.getRollingPolicy()).isInstanceOf(FixedWindowRollingPolicy.class);
assertThat(appender.getRollingPolicy().isStarted()).isTrue();
assertThat(appender.getTriggeringPolicy())
.isInstanceOf(SizeBasedTriggeringPolicy.class)
.satisfies(policy -> assertThat(policy.isStarted()).isTrue())
.extracting("maxFileSize")
.isInstanceOfSatisfying(FileSize.class, maxFileSize -> assertThat(maxFileSize.getSize()).isEqualTo(1024L));
}
@Test
void appenderContextIsSet(@TempDir Path tempDir) {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>();
appenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d.log.gz").toString());
Appender<ILoggingEvent> appender = null;
try {
appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(appender.getContext()).isEqualTo(root.getLoggerContext());
} finally {
if (appender != null) {
appender.stop();
}
}
}
@Test
void appenderNameIsSet(@TempDir Path tempDir) {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>();
appenderFactory.setArchivedLogFilenamePattern(tempDir.resolve("example-%d.log.gz").toString());
Appender<ILoggingEvent> appender = null;
try {
appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(appender.getName()).isEqualTo("async-file-appender");
} finally {
if (appender != null) {
appender.stop();
}
}
}
@Test
void isNeverBlock() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
fileAppenderFactory.setNeverBlock(true);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.isNeverBlock()).isTrue());
}
@Test
void isNotNeverBlock() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
fileAppenderFactory.setNeverBlock(false);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.isNeverBlock()).isFalse());
}
@Test
void defaultIsNotNeverBlock() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
// default neverBlock
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.isNeverBlock()).isFalse());
}
@Test
void overrideBufferSize() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
fileAppenderFactory.setBufferSize(DataSize.kibibytes(256));
AsyncAppender asyncAppender = (AsyncAppender) fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
final Appender<ILoggingEvent> fileAppender = asyncAppender.getAppender("file-appender");
assertThat(fileAppender).isInstanceOf(FileAppender.class);
assertThat(fileAppender)
.extracting("bufferSize")
.isInstanceOfSatisfying(FileSize.class, bufferSize ->
assertThat(bufferSize.getSize()).isEqualTo(fileAppenderFactory.getBufferSize().toBytes()));
}
@Test
void isImmediateFlushed() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
fileAppenderFactory.setImmediateFlush(false);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender)
.extracting(appender -> appender.getAppender("file-appender"))
.satisfies(fileAppender -> assertThat(fileAppender)
.extracting("immediateFlush")
.isEqualTo(fileAppenderFactory.isImmediateFlush())));
fileAppenderFactory.setImmediateFlush(true);
assertThat(fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()))
.isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender)
.extracting(appender -> appender.getAppender("file-appender"))
.satisfies(fileAppender -> assertThat(fileAppender)
.extracting("immediateFlush")
.isEqualTo(fileAppenderFactory.isImmediateFlush())));
}
@Test
void validSetTotalSizeCap() throws IOException, ConfigurationException {
final YamlConfigurationFactory<FileAppenderFactory> factory =
new YamlConfigurationFactory<>(FileAppenderFactory.class, validator, mapper, "dw");
assertThat(factory.build(new ResourceConfigurationSourceProvider(), "yaml/appender_file_cap.yaml")
.buildAppender(new LoggerContext()))
.isInstanceOfSatisfying(RollingFileAppender.class, roller -> assertThat(roller.getRollingPolicy())
.isInstanceOfSatisfying(SizeAndTimeBasedRollingPolicy.class, policy -> assertThat(policy)
.satisfies(p -> assertThat(p)
.extracting("totalSizeCap")
.isInstanceOfSatisfying(FileSize.class, x -> assertThat(x.getSize()).isEqualTo(DataSize.mebibytes(50).toBytes())))
.satisfies(p -> assertThat(p)
.extracting("maxFileSize")
.isInstanceOfSatisfying(FileSize.class, x -> assertThat(x.getSize()).isEqualTo(DataSize.mebibytes(10).toBytes())))
.satisfies(p -> assertThat(p.getMaxHistory()).isEqualTo(5))));
}
@Test
void validSetTotalSizeCapNoMaxFileSize() throws IOException, ConfigurationException {
final YamlConfigurationFactory<FileAppenderFactory> factory =
new YamlConfigurationFactory<>(FileAppenderFactory.class, validator, mapper, "dw");
final FileAppender appender = factory.build(new ResourceConfigurationSourceProvider(), "yaml/appender_file_cap2.yaml")
.buildAppender(new LoggerContext());
assertThat(appender).isInstanceOfSatisfying(RollingFileAppender.class, roller -> assertThat(roller.getRollingPolicy())
.isInstanceOfSatisfying(TimeBasedRollingPolicy.class, policy -> assertThat(policy)
.satisfies(p -> assertThat(p)
.extracting("totalSizeCap")
.isInstanceOfSatisfying(FileSize.class, x ->
assertThat(x.getSize()).isEqualTo(DataSize.mebibytes(50).toBytes())))
.satisfies(p -> assertThat(p.getMaxHistory()).isEqualTo(5))));
}
@Test
void invalidUseOfTotalSizeCap() {
final YamlConfigurationFactory<FileAppenderFactory> factory =
new YamlConfigurationFactory<>(FileAppenderFactory.class, validator, mapper, "dw");
assertThatExceptionOfType(ConfigurationValidationException.class)
.isThrownBy(() -> factory.build(new ResourceConfigurationSourceProvider(), "yaml/appender_file_cap_invalid.yaml"))
.withMessageContaining("totalSizeCap has no effect when using maxFileSize and an archivedLogFilenamePattern " +
"without %d, as archivedFileCount implicitly controls the total size cap");
}
}
| FileAppenderFactoryTest |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/batch/PushLocalSortAggWithSortAndCalcIntoScanRule.java | {
"start": 2725,
"end": 4366
} | class ____ extends PushLocalAggIntoScanRuleBase {
public static final PushLocalSortAggWithSortAndCalcIntoScanRule INSTANCE =
new PushLocalSortAggWithSortAndCalcIntoScanRule();
public PushLocalSortAggWithSortAndCalcIntoScanRule() {
super(
operand(
BatchPhysicalExchange.class,
operand(
BatchPhysicalLocalSortAggregate.class,
operand(
BatchPhysicalSort.class,
operand(
BatchPhysicalCalc.class,
operand(
BatchPhysicalTableSourceScan.class,
none()))))),
"PushLocalSortAggWithSortAndCalcIntoScanRule");
}
@Override
public boolean matches(RelOptRuleCall call) {
BatchPhysicalGroupAggregateBase localAggregate = call.rel(1);
BatchPhysicalCalc calc = call.rel(3);
BatchPhysicalTableSourceScan tableSourceScan = call.rel(4);
return canPushDown(localAggregate, tableSourceScan, calc);
}
@Override
public void onMatch(RelOptRuleCall call) {
BatchPhysicalGroupAggregateBase localSortAgg = call.rel(1);
BatchPhysicalCalc calc = call.rel(3);
BatchPhysicalTableSourceScan oldScan = call.rel(4);
pushLocalAggregateIntoScan(call, localSortAgg, oldScan, calc);
}
}
| PushLocalSortAggWithSortAndCalcIntoScanRule |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableFromUnsafeSource.java | {
"start": 717,
"end": 1040
} | class ____ extends Completable {
final CompletableSource source;
public CompletableFromUnsafeSource(CompletableSource source) {
this.source = source;
}
@Override
protected void subscribeActual(CompletableObserver observer) {
source.subscribe(observer);
}
}
| CompletableFromUnsafeSource |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/TypeConverterRegistryStatsPerformanceTest.java | {
"start": 1011,
"end": 3550
} | class ____ extends ContextTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.setTypeConverterStatisticsEnabled(true);
return context;
}
@Test
public void testTransform() throws Exception {
long noop = context.getTypeConverterRegistry().getStatistics().getNoopCounter();
long attempt = context.getTypeConverterRegistry().getStatistics().getAttemptCounter();
long failed = context.getTypeConverterRegistry().getStatistics().getFailedCounter();
long hit = context.getTypeConverterRegistry().getStatistics().getHitCounter();
long miss = context.getTypeConverterRegistry().getStatistics().getMissCounter();
int size = 1000;
getMockEndpoint("mock:result").expectedMessageCount(size);
for (int i = 0; i < size; i++) {
template.sendBody("direct:start", "World");
}
assertMockEndpointsSatisfied();
long noop2 = context.getTypeConverterRegistry().getStatistics().getNoopCounter();
long attempt2 = context.getTypeConverterRegistry().getStatistics().getAttemptCounter();
long failed2 = context.getTypeConverterRegistry().getStatistics().getFailedCounter();
long hit2 = context.getTypeConverterRegistry().getStatistics().getHitCounter();
long miss2 = context.getTypeConverterRegistry().getStatistics().getMissCounter();
log.info("Noop: before={}, after={}, delta={}", noop, noop2, noop2 - noop);
log.info("Attempt: before={}, after={}, delta={}", attempt, attempt2, attempt2 - attempt);
log.info("Failed: before={}, after={}, delta={}", failed, failed2, failed2 - failed);
log.info("Hit: before={}, after={}, delta={}", hit, hit2, hit2 - hit);
log.info("Miss: before={}, after={}, delta={}", miss, miss2, miss2 - miss);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").transform().method(TypeConverterRegistryStatsPerformanceTest.class, "transformMe")
.bean(TypeConverterRegistryStatsPerformanceTest.class, "transformMeAlso").to("mock:result");
}
};
}
public String transformMe(String in) {
return "Hello " + in;
}
public String transformMeAlso(String in) {
return "Bye " + in;
}
}
| TypeConverterRegistryStatsPerformanceTest |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlClearCursorAction.java | {
"start": 1043,
"end": 2431
} | class ____ extends HandledTransportAction<SqlClearCursorRequest, SqlClearCursorResponse> {
private final PlanExecutor planExecutor;
private final SqlLicenseChecker sqlLicenseChecker;
@Inject
public TransportSqlClearCursorAction(
TransportService transportService,
ActionFilters actionFilters,
PlanExecutor planExecutor,
SqlLicenseChecker sqlLicenseChecker
) {
super(NAME, transportService, actionFilters, SqlClearCursorRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE);
this.planExecutor = planExecutor;
this.sqlLicenseChecker = sqlLicenseChecker;
}
@Override
protected void doExecute(Task task, SqlClearCursorRequest request, ActionListener<SqlClearCursorResponse> listener) {
sqlLicenseChecker.checkIfSqlAllowed(request.mode());
operation(planExecutor, request, listener);
}
public static void operation(
PlanExecutor planExecutor,
SqlClearCursorRequest request,
ActionListener<SqlClearCursorResponse> listener
) {
Cursor cursor = Cursors.decodeFromStringWithZone(request.getCursor(), planExecutor.writeableRegistry()).v1();
planExecutor.cleanCursor(
cursor,
listener.delegateFailureAndWrap((l, success) -> l.onResponse(new SqlClearCursorResponse(success)))
);
}
}
| TransportSqlClearCursorAction |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/transaction/SessionWithinRequestScopeTest.java | {
"start": 647,
"end": 1649
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyEntity.class, PrefixPhysicalNamingStrategy.class)
.addAsResource(EmptyAsset.INSTANCE, "import.sql"));
@Inject
Session session;
@BeforeEach
public void activateRequestContext() {
Arc.container().requestContext().activate();
}
@Test
public void read() {
assertEquals(0L, session
.createSelectionQuery("SELECT entity FROM MyEntity entity WHERE name IS NULL", MyEntity.class)
.getResultCount());
}
@Test
public void write() {
assertThatThrownBy(() -> session.persist(new MyEntity("john")))
.hasMessageContaining("Transaction is not active");
}
@AfterEach
public void terminateRequestContext() {
Arc.container().requestContext().terminate();
}
}
| SessionWithinRequestScopeTest |
java | apache__camel | components/camel-grpc/src/main/java/org/apache/camel/component/grpc/server/GrpcHeaderInterceptor.java | {
"start": 1229,
"end": 2017
} | class ____ implements ServerInterceptor {
public static final Context.Key<String> USER_AGENT_CONTEXT_KEY = Context.key(GrpcConstants.GRPC_USER_AGENT_HEADER);
public static final Context.Key<String> CONTENT_TYPE_CONTEXT_KEY = Context.key(Exchange.CONTENT_TYPE);
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) {
Context context = Context.current()
.withValue(USER_AGENT_CONTEXT_KEY, requestHeaders.get(GrpcUtil.USER_AGENT_KEY))
.withValue(CONTENT_TYPE_CONTEXT_KEY, requestHeaders.get(GrpcUtil.CONTENT_TYPE_KEY));
return Contexts.interceptCall(context, call, requestHeaders, next);
}
}
| GrpcHeaderInterceptor |
java | apache__spark | sql/hive/src/test/java/org/apache/spark/sql/hive/test/Complex.java | {
"start": 25411,
"end": 25590
} | class ____ implements SchemeFactory {
public ComplexStandardScheme getScheme() {
return new ComplexStandardScheme();
}
}
private static | ComplexStandardSchemeFactory |
java | apache__camel | components/camel-metrics/src/main/java/org/apache/camel/component/metrics/TimerProducer.java | {
"start": 1147,
"end": 3356
} | class ____ extends AbstractMetricsProducer {
private static final Logger LOG = LoggerFactory.getLogger(TimerProducer.class);
public TimerProducer(MetricsEndpoint endpoint) {
super(endpoint);
}
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName)
throws Exception {
Message in = exchange.getIn();
MetricsTimerAction action = endpoint.getAction();
MetricsTimerAction finalAction = in.getHeader(HEADER_TIMER_ACTION, action, MetricsTimerAction.class);
if (finalAction == MetricsTimerAction.start) {
handleStart(exchange, registry, metricsName);
} else if (finalAction == MetricsTimerAction.stop) {
handleStop(exchange, metricsName);
} else {
LOG.warn("No action provided for timer \"{}\"", metricsName);
}
}
void handleStart(Exchange exchange, MetricRegistry registry, String metricsName) {
String propertyName = getPropertyName(metricsName);
Timer.Context context = getTimerContextFromExchange(exchange, propertyName);
if (context == null) {
Timer timer = registry.timer(metricsName);
context = timer.time();
exchange.setProperty(propertyName, context);
} else {
LOG.warn("Timer \"{}\" already running", metricsName);
}
}
void handleStop(Exchange exchange, String metricsName) {
String propertyName = getPropertyName(metricsName);
Timer.Context context = getTimerContextFromExchange(exchange, propertyName);
if (context != null) {
context.stop();
exchange.removeProperty(propertyName);
} else {
LOG.warn("Timer \"{}\" not found", metricsName);
}
}
String getPropertyName(String metricsName) {
return new StringBuilder("timer")
.append(":")
.append(metricsName)
.toString();
}
Timer.Context getTimerContextFromExchange(Exchange exchange, String propertyName) {
return exchange.getProperty(propertyName, Timer.Context.class);
}
}
| TimerProducer |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/SimpleResourceInfo.java | {
"start": 430,
"end": 494
} | interface ____ {
/**
* Get the resource | SimpleResourceInfo |
java | spring-projects__spring-boot | module/spring-boot-neo4j/src/main/java/org/springframework/boot/neo4j/autoconfigure/Neo4jProperties.java | {
"start": 2297,
"end": 3395
} | class ____ {
/**
* Login user of the server.
*/
private @Nullable String username;
/**
* Login password of the server.
*/
private @Nullable String password;
/**
* Realm to connect to.
*/
private @Nullable String realm;
/**
* Kerberos ticket for connecting to the database. Mutual exclusive with a given
* username.
*/
private @Nullable String kerberosTicket;
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getRealm() {
return this.realm;
}
public void setRealm(@Nullable String realm) {
this.realm = realm;
}
public @Nullable String getKerberosTicket() {
return this.kerberosTicket;
}
public void setKerberosTicket(@Nullable String kerberosTicket) {
this.kerberosTicket = kerberosTicket;
}
}
public static | Authentication |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/http/RequestOptionsTest.java | {
"start": 854,
"end": 4229
} | class ____ {
@Test
public void testDefaults() {
RequestOptions options = new RequestOptions();
assertEquals(RequestOptions.DEFAULT_SERVER, options.getServer());
assertEquals(RequestOptions.DEFAULT_HTTP_METHOD, options.getMethod());
assertEquals(RequestOptions.DEFAULT_HOST, options.getHost());
assertEquals(RequestOptions.DEFAULT_PORT, options.getPort());
assertEquals(RequestOptions.DEFAULT_SSL, options.isSsl());
assertEquals(RequestOptions.DEFAULT_URI, options.getURI());
assertEquals(RequestOptions.DEFAULT_FOLLOW_REDIRECTS, options.getFollowRedirects());
assertEquals(RequestOptions.DEFAULT_TIMEOUT, options.getTimeout());
assertEquals(RequestOptions.DEFAULT_CONNECT_TIMEOUT, options.getConnectTimeout());
assertEquals(RequestOptions.DEFAULT_IDLE_TIMEOUT, options.getIdleTimeout());
}
@Test
public void testCopy() {
RequestOptions options = new RequestOptions()
.setMethod(HttpMethod.PUT)
.setPort(8443)
.setSsl(true)
.setFollowRedirects(true);
RequestOptions copy = new RequestOptions(options);
assertEquals(options.getMethod(), copy.getMethod());
assertEquals(options.getPort(), copy.getPort());
assertEquals(options.isSsl(), copy.isSsl());
assertEquals(options.getFollowRedirects(), copy.getFollowRedirects());
}
@Test
public void testToJson() {
RequestOptions options = new RequestOptions()
.setMethod(HttpMethod.PUT)
.setPort(8443)
.setSsl(true)
.setFollowRedirects(true)
.addHeader("key", "value")
.addHeader("foo", Arrays.asList("bar", "baz"));
JsonObject expected = new JsonObject()
.put("timeout", RequestOptions.DEFAULT_TIMEOUT)
.put("connectTimeout", RequestOptions.DEFAULT_CONNECT_TIMEOUT)
.put("idleTimeout", RequestOptions.DEFAULT_IDLE_TIMEOUT)
.put("uri", RequestOptions.DEFAULT_URI)
.put("method", "PUT")
.put("port", 8443)
.put("ssl", true)
.put("followRedirects", true)
.put("headers", new JsonObject()
.put("key", "value")
.put("foo", new JsonArray().add("bar").add("baz"))
);
assertEquals(expected, options.toJson());
}
@Test
public void testFromJson() {
JsonObject json = new JsonObject()
.put("method", "PUT")
.put("port", 8443)
.put("ssl", true)
.put("followRedirects", true)
.put("headers", new JsonObject()
.put("key", "value")
.put("foo", new JsonArray().add("bar").add("baz"))
);
RequestOptions options = new RequestOptions(json);
assertEquals(HttpMethod.PUT, options.getMethod());
assertEquals(Integer.valueOf(8443), options.getPort());
assertTrue(options.isSsl());
assertTrue(options.getFollowRedirects());
MultiMap headers = options.getHeaders();
assertEquals(headers.toString(), 2, headers.size());
assertEquals(Collections.singletonList("value"), headers.getAll("key"));
assertEquals(Arrays.asList("bar", "baz"), headers.getAll("foo"));
}
@Test
public void testHeaderNameValidation() {
assertThrows(IllegalArgumentException.class, () -> new RequestOptions().addHeader("=", "invalid header name"));
}
@Test
public void testHeaderValueValidation() {
assertThrows(IllegalArgumentException.class, () -> new RequestOptions().addHeader("invalid-header-value", "\r"));
}
}
| RequestOptionsTest |
java | micronaut-projects__micronaut-core | http-server-netty/src/main/java/io/micronaut/http/server/netty/handler/Compressor.java | {
"start": 8397,
"end": 8787
} | enum ____ {
BR(HttpHeaderValues.BR),
ZSTD(HttpHeaderValues.ZSTD),
SNAPPY(HttpHeaderValues.SNAPPY),
GZIP(HttpHeaderValues.GZIP),
DEFLATE(HttpHeaderValues.DEFLATE);
final CharSequence contentEncoding;
Algorithm(CharSequence contentEncoding) {
this.contentEncoding = contentEncoding;
}
}
static final | Algorithm |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/IlmHealthIndicatorService.java | {
"start": 18421,
"end": 22524
} | class ____ {
private String action;
private TimeValue maxTimeOn = null;
static Builder actionRule(String action) {
var builder = new Builder();
builder.action = action;
return builder;
}
Builder maxTimeOnAction(TimeValue maxTimeOn) {
this.maxTimeOn = maxTimeOn;
return this;
}
RuleConfig stepRules(StepRule... stepRules) {
assert stepRules.length > 0;
if (stepRules.length == 1) {
return new ActionRule(action, maxTimeOn).and(stepRules[0]);
} else {
RuleConfig stepRule = stepRules[0];
for (var i = 1; i < stepRules.length; i++) {
stepRule = stepRule.or(stepRules[i]);
}
return new ActionRule(action, maxTimeOn).and(stepRule);
}
}
RuleConfig noStepRules() {
return new ActionRule(action, maxTimeOn);
}
}
}
/**
* Record defining a rule that will check the current action that an ILM-managed index is into.
*
* @param action The action against which the rule will be checked.
* @param maxTimeOn Maximum time that an index should spend on this action.
*/
record ActionRule(String action, TimeValue maxTimeOn) implements RuleConfig {
@Override
public boolean test(Long now, IndexMetadata indexMetadata) {
var currentAction = indexMetadata.getLifecycleExecutionState().action();
if (maxTimeOn == null) {
return action.equals(currentAction);
} else {
return action.equals(currentAction)
&& maxTimeOn.compareTo(RuleConfig.getElapsedTime(now, indexMetadata.getLifecycleExecutionState().actionTime())) < 0;
}
}
}
/**
* Record defining a rule that will check the current step that an ILM-managed index is into.
*
* @param step The step against which the rule will be checked.
* @param maxTimeOn Maximum time that an index should spend on this step.
* @param maxRetries Maximum number of times that a step should be retried.
*/
public record StepRule(String step, TimeValue maxTimeOn, Long maxRetries) implements RuleConfig {
public StepRule {
if (maxTimeOn == null && maxRetries == null) {
throw new IllegalArgumentException("At least one of [maxTimeOne or maxRetries] must be defined.");
}
}
static StepRule stepRuleFullChecks(String name, TimeValue maxTimeOn, long maxRetries) {
return new StepRule(name, maxTimeOn, maxRetries);
}
static StepRule stepRuleOnlyCheckPassedTime(String name, TimeValue maxTimeOn) {
return new StepRule(name, maxTimeOn, null);
}
static StepRule stepRuleOnlyCheckRetries(String name, long maxRetries) {
return new StepRule(name, null, maxRetries);
}
@Override
public boolean test(Long now, IndexMetadata indexMetadata) {
var failedStepRetryCount = indexMetadata.getLifecycleExecutionState().failedStepRetryCount();
return step.equals(indexMetadata.getLifecycleExecutionState().step())
&& (maxTimeOn != null
&& maxTimeOn.compareTo(RuleConfig.getElapsedTime(now, indexMetadata.getLifecycleExecutionState().stepTime())) < 0
|| (maxRetries != null && failedStepRetryCount != null && failedStepRetryCount > maxRetries));
}
}
/**
* This method solely exists because we are not making ILM properly project-aware and it's not worth the investment of altering this
* health indicator to be project-aware.
*/
@NotMultiProjectCapable
private static ProjectMetadata getDefaultILMProject(ClusterState state) {
return state.metadata().getProject(ProjectId.DEFAULT);
}
}
| Builder |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/strategy/AuditStrategy.java | {
"start": 730,
"end": 2810
} | interface ____ extends org.hibernate.envers.strategy.spi.AuditStrategy {
/**
* Perform the persistence of audited data for regular entities.
*
* @param session Session, which can be used to persist the data.
* @param entityName Name of the entity, in which the audited change happens
* @param enversService The EnversService
* @param id Id of the entity.
* @param data Audit data to persist
* @param revision Current revision data
* @deprecated use {@link org.hibernate.envers.strategy.spi.AuditStrategy#perform(org.hibernate.engine.spi.SharedSessionContractImplementor, String, Configuration, Object, Object, Object)}
*/
@Deprecated(since = "5.2.1")
default void perform(
Session session,
String entityName,
EnversService enversService,
Object id,
Object data,
Object revision) {
perform(
(SharedSessionContractImplementor) session,
entityName,
enversService.getConfig(),
id,
data,
revision
);
}
/**
* Perform the persistence of audited data for collection ("middle") entities.
*
* @param session Session, which can be used to persist the data.
* @param entityName Name of the entity, in which the audited change happens.
* @param propertyName The name of the property holding the persistent collection
* @param enversService The EnversService
* @param persistentCollectionChangeData Collection change data to be persisted.
* @param revision Current revision data
* @deprecated use {@link #performCollectionChange(SharedSessionContractImplementor, String, String, Configuration, PersistentCollectionChangeData, Object)}
*/
@Deprecated(since = "5.2.1")
default void performCollectionChange(
Session session,
String entityName,
String propertyName,
EnversService enversService,
PersistentCollectionChangeData persistentCollectionChangeData,
Object revision) {
performCollectionChange(
(SharedSessionContractImplementor) session,
entityName,
propertyName,
enversService.getConfig(),
persistentCollectionChangeData,
revision
);
}
}
| AuditStrategy |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/IsPodmanWorking.java | {
"start": 286,
"end": 649
} | class ____ extends IsContainerRuntimeWorking {
public IsPodmanWorking() {
this(false);
}
public IsPodmanWorking(boolean silent) {
super(List.of(
new TestContainersStrategy(silent),
new DockerHostStrategy(silent),
new PodmanBinaryStrategy(silent)));
}
private static | IsPodmanWorking |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/FieldTypeLookupTests.java | {
"start": 1349,
"end": 26239
} | class ____ extends ESTestCase {
public void testEmpty() {
FieldTypeLookup lookup = new FieldTypeLookup(emptyList(), emptyList());
assertNull(lookup.get("foo"));
Collection<String> names = lookup.getMatchingFieldNames("foo");
assertNotNull(names);
assertThat(names, hasSize(0));
}
public void testAddNewField() {
MockFieldMapper f = new MockFieldMapper("foo");
FieldTypeLookup lookup = new FieldTypeLookup(Collections.singletonList(f), emptyList());
assertNull(lookup.get("bar"));
assertEquals(f.fieldType(), lookup.get("foo"));
}
public void testAddFieldAlias() {
MockFieldMapper field = new MockFieldMapper("foo");
FieldAliasMapper alias = new FieldAliasMapper("alias", "alias", "foo");
FieldTypeLookup lookup = new FieldTypeLookup(Collections.singletonList(field), Collections.singletonList(alias));
MappedFieldType aliasType = lookup.get("alias");
assertEquals(field.fieldType(), aliasType);
}
public void testGetMatchingFieldNames() {
FlattenedFieldMapper flattened = createFlattenedMapper("flattened");
MockFieldMapper field1 = new MockFieldMapper("foo");
MockFieldMapper field2 = new MockFieldMapper("bar");
MockFieldMapper field3 = new MockFieldMapper("baz");
FieldAliasMapper alias1 = new FieldAliasMapper("food", "food", "foo");
FieldAliasMapper alias2 = new FieldAliasMapper("barometer", "barometer", "bar");
TestRuntimeField runtimeField = new TestRuntimeField("baz", "type");
TestRuntimeField multi = new TestRuntimeField(
"flat",
List.of(
new TestRuntimeField.TestRuntimeFieldType("flat.first", "first"),
new TestRuntimeField.TestRuntimeFieldType("flat.second", "second")
)
);
FieldTypeLookup lookup = new FieldTypeLookup(
List.of(field1, field2, field3, flattened),
List.of(alias1, alias2),
List.of(),
List.of(runtimeField, multi)
);
{
Collection<String> names = lookup.getMatchingFieldNames("*");
assertThat(names, containsInAnyOrder("foo", "food", "bar", "baz", "barometer", "flattened", "flat.first", "flat.second"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("b*");
assertThat(names, containsInAnyOrder("bar", "baz", "barometer"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("fl*");
assertThat(names, containsInAnyOrder("flattened", "flat.first", "flat.second"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("baro.any*");
assertThat(names, hasSize(0));
}
{
Collection<String> names = lookup.getMatchingFieldNames("foo*");
assertThat(names, containsInAnyOrder("foo", "food"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("flattened.anything");
assertThat(names, containsInAnyOrder("flattened.anything"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("flat.first");
assertThat(names, containsInAnyOrder("flat.first"));
}
{
Collection<String> names = lookup.getMatchingFieldNames("flat.second");
assertThat(names, containsInAnyOrder("flat.second"));
}
}
public void testSourcePathWithMultiFields() {
MockFieldMapper field = new MockFieldMapper.Builder("field").addMultiField(new MockFieldMapper.Builder("field.subfield1"))
.addMultiField(new MockFieldMapper.Builder("field.subfield2.subfield3"))
.build(MapperBuilderContext.root(false, false));
// Adding a subfield that is not multi-field
MockFieldMapper subfield = new MockFieldMapper.Builder("field.subfield4").build(MapperBuilderContext.root(false, false));
FieldTypeLookup lookup = new FieldTypeLookup(List.of(field, subfield), emptyList());
assertEquals(Set.of("field"), lookup.sourcePaths("field"));
assertEquals(Set.of("field"), lookup.sourcePaths("field.subfield1"));
assertEquals(Set.of("field"), lookup.sourcePaths("field.subfield2.subfield3"));
assertEquals(Set.of("field.subfield4"), lookup.sourcePaths("field.subfield4"));
}
public void testSourcePathsWithCopyTo() {
MockFieldMapper field = new MockFieldMapper.Builder("field").addMultiField(new MockFieldMapper.Builder("field.subfield1"))
.build(MapperBuilderContext.root(false, false));
MockFieldMapper nestedField = new MockFieldMapper.Builder("field.nested").addMultiField(
new MockFieldMapper.Builder("field.nested.subfield1")
).build(MapperBuilderContext.root(false, false));
MockFieldMapper otherField = new MockFieldMapper.Builder("other_field").copyTo("field")
.copyTo("field.nested")
.build(MapperBuilderContext.root(false, false));
MockFieldMapper otherNestedField = new MockFieldMapper.Builder("other_field.nested").copyTo("field")
.copyTo("field.nested")
.build(MapperBuilderContext.root(false, false));
FieldTypeLookup lookup = new FieldTypeLookup(Arrays.asList(field, nestedField, otherField, otherNestedField), emptyList());
assertEquals(Set.of("other_field", "other_field.nested", "field"), lookup.sourcePaths("field"));
assertEquals(Set.of("other_field", "other_field.nested", "field"), lookup.sourcePaths("field.subfield1"));
assertEquals(Set.of("other_field", "other_field.nested", "field.nested"), lookup.sourcePaths("field.nested"));
assertEquals(Set.of("other_field", "other_field.nested", "field.nested"), lookup.sourcePaths("field.nested.subfield1"));
}
public void testRuntimeFieldsLookup() {
MockFieldMapper concrete = new MockFieldMapper("concrete");
TestRuntimeField runtimeLong = new TestRuntimeField("multi.outside", "date");
TestRuntimeField runtime = new TestRuntimeField("string", "type");
TestRuntimeField multi = new TestRuntimeField(
"multi",
List.of(
new TestRuntimeField.TestRuntimeFieldType("multi.string", "string"),
new TestRuntimeField.TestRuntimeFieldType("multi.long", "long")
)
);
FieldTypeLookup fieldTypeLookup = new FieldTypeLookup(
List.of(concrete),
emptyList(),
emptyList(),
List.of(runtime, runtimeLong, multi)
);
assertThat(fieldTypeLookup.get("concrete"), instanceOf(MockFieldMapper.FakeFieldType.class));
assertThat(fieldTypeLookup.get("string"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("string").typeName(), equalTo("type"));
assertThat(fieldTypeLookup.get("multi"), nullValue());
assertThat(fieldTypeLookup.get("multi.string"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("multi.string").typeName(), equalTo("string"));
assertThat(fieldTypeLookup.get("multi.long"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("multi.long").typeName(), equalTo("long"));
assertThat(fieldTypeLookup.get("multi.outside"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("multi.outside").typeName(), equalTo("date"));
assertThat(fieldTypeLookup.get("multi.anything"), nullValue());
}
public void testRuntimeFieldsOverrideConcreteFields() {
FlattenedFieldMapper flattened = createFlattenedMapper("flattened");
MockFieldMapper field = new MockFieldMapper("field");
MockFieldMapper subfield = new MockFieldMapper("object.subfield");
MockFieldMapper concrete = new MockFieldMapper("concrete");
TestRuntimeField fieldOverride = new TestRuntimeField("field", "string");
TestRuntimeField subfieldOverride = new TestRuntimeField(
"object",
Collections.singleton(new TestRuntimeField.TestRuntimeFieldType("object.subfield", "leaf"))
);
TestRuntimeField runtime = new TestRuntimeField("runtime", "type");
TestRuntimeField flattenedRuntime = new TestRuntimeField("flattened.runtime", "type");
FieldTypeLookup fieldTypeLookup = new FieldTypeLookup(
List.of(field, concrete, subfield, flattened),
emptyList(),
emptyList(),
List.of(fieldOverride, runtime, subfieldOverride, flattenedRuntime)
);
assertThat(fieldTypeLookup.get("field"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("field").typeName(), equalTo("string"));
assertThat(fieldTypeLookup.get("object.subfield"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("object.subfield").typeName(), equalTo("leaf"));
assertThat(fieldTypeLookup.get("concrete"), instanceOf(MockFieldMapper.FakeFieldType.class));
assertThat(fieldTypeLookup.get("runtime"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
assertThat(fieldTypeLookup.get("runtime").typeName(), equalTo("type"));
assertThat(fieldTypeLookup.get("flattened.anything"), instanceOf(FlattenedFieldMapper.KeyedFlattenedFieldType.class));
assertThat(fieldTypeLookup.get("flattened.runtime"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
}
public void testRuntimeFieldsSourcePaths() {
// we test that runtime fields are treated like any other field by sourcePaths, although sourcePaths
// should never be called for runtime fields as they are not in _source
MockFieldMapper field1 = new MockFieldMapper("field1");
MockFieldMapper concrete = new MockFieldMapper("concrete");
TestRuntimeField field2 = new TestRuntimeField("field2", "type");
TestRuntimeField subfield = new TestRuntimeField("object.subfield", "type");
FieldTypeLookup fieldTypeLookup = new FieldTypeLookup(
List.of(field1, concrete),
emptyList(),
emptyList(),
List.of(field2, subfield)
);
{
Set<String> sourcePaths = fieldTypeLookup.sourcePaths("field1");
assertEquals(1, sourcePaths.size());
assertTrue(sourcePaths.contains("field1"));
}
{
Set<String> sourcePaths = fieldTypeLookup.sourcePaths("field2");
assertEquals(1, sourcePaths.size());
assertTrue(sourcePaths.contains("field2"));
}
{
Set<String> sourcePaths = fieldTypeLookup.sourcePaths("object.subfield");
assertEquals(1, sourcePaths.size());
assertTrue(sourcePaths.contains("object.subfield"));
}
}
public void testFlattenedLookup() {
String fieldName = "object1.object2.field";
FlattenedFieldMapper mapper = createFlattenedMapper(fieldName);
FieldTypeLookup lookup = new FieldTypeLookup(singletonList(mapper), emptyList());
assertEquals(mapper.fieldType(), lookup.get(fieldName));
String objectKey = "key1.key2";
String searchFieldName = fieldName + "." + objectKey;
MappedFieldType searchFieldType = lookup.get(searchFieldName);
assertNotNull(searchFieldType);
assertThat(searchFieldType, Matchers.instanceOf(FlattenedFieldMapper.KeyedFlattenedFieldType.class));
FlattenedFieldMapper.KeyedFlattenedFieldType keyedFieldType = (FlattenedFieldMapper.KeyedFlattenedFieldType) searchFieldType;
assertEquals(objectKey, keyedFieldType.key());
assertThat(lookup.getMatchingFieldNames("object1.*"), contains("object1.object2.field"));
// We can directly find dynamic subfields
assertThat(lookup.getMatchingFieldNames("object1.object2.field.foo"), contains("object1.object2.field.foo"));
// But you can't generate dynamic subfields from a wildcard pattern
assertThat(lookup.getMatchingFieldNames("object1.object2.field.foo*"), hasSize(0));
}
public void testFlattenedLookupWithAlias() {
String fieldName = "object1.object2.field";
FlattenedFieldMapper mapper = createFlattenedMapper(fieldName);
String aliasName = "alias";
FieldAliasMapper alias = new FieldAliasMapper(aliasName, aliasName, fieldName);
FieldTypeLookup lookup = new FieldTypeLookup(singletonList(mapper), singletonList(alias), emptyList(), emptyList());
assertEquals(mapper.fieldType(), lookup.get(aliasName));
String objectKey = "key1.key2";
String searchFieldName = aliasName + "." + objectKey;
MappedFieldType searchFieldType = lookup.get(searchFieldName);
assertNotNull(searchFieldType);
assertThat(searchFieldType, Matchers.instanceOf(FlattenedFieldMapper.KeyedFlattenedFieldType.class));
FlattenedFieldMapper.KeyedFlattenedFieldType keyedFieldType = (FlattenedFieldMapper.KeyedFlattenedFieldType) searchFieldType;
assertEquals(objectKey, keyedFieldType.key());
}
public void testFlattenedLookupWithMultipleFields() {
String field1 = "object1.object2.field";
String field2 = "object1.field";
String field3 = "object2.field";
FlattenedFieldMapper mapper1 = createFlattenedMapper(field1);
FlattenedFieldMapper mapper2 = createFlattenedMapper(field2);
FlattenedFieldMapper mapper3 = createFlattenedMapper(field3);
FieldTypeLookup lookup = new FieldTypeLookup(Arrays.asList(mapper1, mapper2), emptyList());
assertNotNull(lookup.get(field1 + ".some.key"));
assertNotNull(lookup.get(field2 + ".some.key"));
lookup = new FieldTypeLookup(Arrays.asList(mapper1, mapper2, mapper3), emptyList());
assertNotNull(lookup.get(field1 + ".some.key"));
assertNotNull(lookup.get(field2 + ".some.key"));
assertNotNull(lookup.get(field3 + ".some.key"));
}
public void testUnmappedLookupWithDots() {
FieldTypeLookup lookup = new FieldTypeLookup(emptyList(), emptyList());
assertNull(lookup.get("object.child"));
}
public void testMaxDynamicKeyDepth() {
{
FieldTypeLookup lookup = new FieldTypeLookup(emptyList(), emptyList());
assertEquals(0, lookup.getMaxParentPathDots());
}
// Add a flattened object field.
{
String name = "object1.object2.field";
FieldTypeLookup lookup = new FieldTypeLookup(Collections.singletonList(createFlattenedMapper(name)), emptyList());
assertEquals(2, lookup.getMaxParentPathDots());
}
// Add a short alias to that field.
{
String name = "object1.object2.field";
FieldTypeLookup lookup = new FieldTypeLookup(
Collections.singletonList(createFlattenedMapper(name)),
Collections.singletonList(new FieldAliasMapper("alias", "alias", "object1.object2.field"))
);
assertEquals(2, lookup.getMaxParentPathDots());
}
// Add a longer alias to that field.
{
String name = "object1.object2.field";
FieldTypeLookup lookup = new FieldTypeLookup(
Collections.singletonList(createFlattenedMapper(name)),
Collections.singletonList(new FieldAliasMapper("alias", "object1.object2.object3.alias", "object1.object2.field"))
);
assertEquals(2, lookup.getMaxParentPathDots());
}
}
public void testRuntimeFieldNameClashes() {
{
IllegalArgumentException iae = expectThrows(
IllegalArgumentException.class,
() -> new FieldTypeLookup(
emptyList(),
emptyList(),
emptyList(),
List.of(new TestRuntimeField("field", "type"), new TestRuntimeField("field", "long"))
)
);
assertEquals(iae.getMessage(), "Found two runtime fields with same name [field]");
}
{
TestRuntimeField multi = new TestRuntimeField(
"multi",
Collections.singleton(new TestRuntimeField.TestRuntimeFieldType("multi.first", "leaf"))
);
TestRuntimeField runtime = new TestRuntimeField("multi.first", "runtime");
IllegalArgumentException iae = expectThrows(
IllegalArgumentException.class,
() -> new FieldTypeLookup(emptyList(), emptyList(), emptyList(), List.of(multi, runtime))
);
assertEquals(iae.getMessage(), "Found two runtime fields with same name [multi.first]");
}
{
TestRuntimeField multi = new TestRuntimeField(
"multi",
List.of(
new TestRuntimeField.TestRuntimeFieldType("multi", "leaf"),
new TestRuntimeField.TestRuntimeFieldType("multi", "leaf")
)
);
IllegalArgumentException iae = expectThrows(
IllegalArgumentException.class,
() -> new FieldTypeLookup(emptyList(), emptyList(), emptyList(), List.of(multi))
);
assertEquals(iae.getMessage(), "Found two runtime fields with same name [multi]");
}
}
public void testRuntimeFieldNameOutsideContext() {
{
TestRuntimeField multi = new TestRuntimeField(
"multi",
List.of(
new TestRuntimeField.TestRuntimeFieldType("first", "leaf"),
new TestRuntimeField.TestRuntimeFieldType("second", "leaf"),
new TestRuntimeField.TestRuntimeFieldType("multi.third", "leaf")
)
);
IllegalStateException ise = expectThrows(
IllegalStateException.class,
() -> new FieldTypeLookup(emptyList(), emptyList(), emptyList(), Collections.singletonList(multi))
);
assertEquals("Found sub-fields with name not belonging to the parent field they are part of [first, second]", ise.getMessage());
}
{
TestRuntimeField multi = new TestRuntimeField(
"multi",
List.of(
new TestRuntimeField.TestRuntimeFieldType("multi.", "leaf"),
new TestRuntimeField.TestRuntimeFieldType("multi.f", "leaf")
)
);
IllegalStateException ise = expectThrows(
IllegalStateException.class,
() -> new FieldTypeLookup(emptyList(), emptyList(), emptyList(), Collections.singletonList(multi))
);
assertEquals("Found sub-fields with name not belonging to the parent field they are part of [multi.]", ise.getMessage());
}
}
private static FlattenedFieldMapper createFlattenedMapper(String fieldName) {
return new FlattenedFieldMapper.Builder(fieldName).build(MapperBuilderContext.root(false, false));
}
private PassThroughObjectMapper createPassThroughMapper(String name, Map<String, Mapper> mappers, int priority) {
return new PassThroughObjectMapper(
name,
name,
Explicit.EXPLICIT_TRUE,
Optional.empty(),
ObjectMapper.Dynamic.FALSE,
mappers,
Explicit.EXPLICIT_FALSE,
priority
);
}
public void testAddRootAliasesForPassThroughFields() {
MockFieldMapper foo = new MockFieldMapper("attributes.foo");
MockFieldMapper bar = new MockFieldMapper(
new MockFieldMapper.FakeFieldType("attributes.much.more.deeply.nested.bar"),
"much.more.deeply.nested.bar"
);
PassThroughObjectMapper attributes = createPassThroughMapper(
"attributes",
Map.of("foo", foo, "much.more.deeply.nested.bar", bar),
0
);
MockFieldMapper baz = new MockFieldMapper("resource.attributes.baz");
MockFieldMapper bag = new MockFieldMapper(
new MockFieldMapper.FakeFieldType("resource.attributes.much.more.deeply.nested.bag"),
"much.more.deeply.nested.bag"
);
PassThroughObjectMapper resourceAttributes = createPassThroughMapper(
"resource.attributes",
Map.of("baz", baz, "much.more.deeply.nested.bag", bag),
1
);
FieldTypeLookup lookup = new FieldTypeLookup(
List.of(foo, bar, baz, bag),
List.of(),
List.of(attributes, resourceAttributes),
List.of()
);
assertEquals(foo.fieldType(), lookup.get("foo"));
assertEquals(bar.fieldType(), lookup.get("much.more.deeply.nested.bar"));
assertEquals(baz.fieldType(), lookup.get("baz"));
assertEquals(bag.fieldType(), lookup.get("much.more.deeply.nested.bag"));
}
public void testNoPassThroughField() {
MockFieldMapper field = new MockFieldMapper("labels.foo");
PassThroughObjectMapper attributes = createPassThroughMapper("attributes", Map.of(), 0);
FieldTypeLookup lookup = new FieldTypeLookup(List.of(field), List.of(), List.of(attributes), List.of());
assertNull(lookup.get("foo"));
}
public void testAddRootAliasForConflictingPassThroughFields() {
MockFieldMapper attributeField = new MockFieldMapper("attributes.foo");
PassThroughObjectMapper attributes = createPassThroughMapper("attributes", Map.of("foo", attributeField), 1);
MockFieldMapper resourceAttributeField = new MockFieldMapper("resource.attributes.foo");
PassThroughObjectMapper resourceAttributes = createPassThroughMapper(
"resource.attributes",
Map.of("foo", resourceAttributeField),
0
);
FieldTypeLookup lookup = new FieldTypeLookup(
randomizedList(attributeField, resourceAttributeField),
List.of(),
randomizedList(attributes, resourceAttributes),
List.of()
);
assertEquals(attributeField.fieldType(), lookup.get("foo"));
}
public void testNoRootAliasForPassThroughFieldOnConflictingField() {
MockFieldMapper attributeFoo = new MockFieldMapper("attributes.foo");
MockFieldMapper resourceAttributeFoo = new MockFieldMapper("resource.attributes.foo");
MockFieldMapper foo = new MockFieldMapper("foo");
PassThroughObjectMapper attributes = createPassThroughMapper("attributes", Map.of("foo", attributeFoo), 0);
PassThroughObjectMapper resourceAttributes = createPassThroughMapper("resource.attributes", Map.of("foo", resourceAttributeFoo), 1);
FieldTypeLookup lookup = new FieldTypeLookup(
randomizedList(foo, attributeFoo, resourceAttributeFoo),
List.of(),
randomizedList(attributes, resourceAttributes),
List.of()
);
assertEquals(foo.fieldType(), lookup.get("foo"));
}
public void testDotCount() {
assertEquals(0, FieldTypeLookup.dotCount(""));
assertEquals(1, FieldTypeLookup.dotCount("."));
assertEquals(2, FieldTypeLookup.dotCount(".."));
assertEquals(3, FieldTypeLookup.dotCount("..."));
assertEquals(4, FieldTypeLookup.dotCount("...."));
assertEquals(0, FieldTypeLookup.dotCount("foo"));
assertEquals(1, FieldTypeLookup.dotCount("foo.bar"));
assertEquals(2, FieldTypeLookup.dotCount("foo.bar.baz"));
assertEquals(3, FieldTypeLookup.dotCount("foo.bar.baz.bob"));
assertEquals(4, FieldTypeLookup.dotCount("foo.bar.baz.bob."));
assertEquals(4, FieldTypeLookup.dotCount("foo..bar.baz.bob"));
assertEquals(5, FieldTypeLookup.dotCount("foo..bar..baz.bob"));
assertEquals(6, FieldTypeLookup.dotCount("foo..bar..baz.bob."));
int times = atLeast(50);
for (int i = 0; i < times; i++) {
byte[] bytes = new byte[randomInt(1024)];
random().nextBytes(bytes);
String s = new String(bytes, StandardCharsets.UTF_8);
int expected = s.chars().map(c -> c == '.' ? 1 : 0).sum();
assertEquals(expected, FieldTypeLookup.dotCount(s));
}
}
@SafeVarargs
@SuppressWarnings("varargs")
static <T> List<T> randomizedList(T... values) {
ArrayList<T> list = new ArrayList<>(Arrays.asList(values));
Collections.shuffle(list, random());
return list;
}
}
| FieldTypeLookupTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/defaultbean/DefaultClassBeanTest.java | {
"start": 2568,
"end": 2834
} | class ____ {
@Produces
GreetingBean greetingBean() {
return new GreetingBean() {
@Override
String greet() {
return "hello";
}
};
}
}
| Producer |
java | google__dagger | javatests/dagger/internal/codegen/LazyClassKeyMapBindingComponentProcessorTest.java | {
"start": 12085,
"end": 12339
} | class ____.FooKey");
});
}
@Test
public void testProguardFile_nestedModule() throws Exception {
Source fooKey =
CompilerTests.javaSource(
"test.FooKey",
"package test;",
"",
" | test |
java | micronaut-projects__micronaut-core | function/src/main/java/io/micronaut/function/executor/FunctionExecutor.java | {
"start": 905,
"end": 1155
} | interface ____<I, O> {
/**
* Execute the function configured by {@link io.micronaut.function.LocalFunctionRegistry#FUNCTION_NAME}.
*
* @param input The input
* @return The output
*/
O execute(I input);
}
| FunctionExecutor |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/ReInitializeContainerResponse.java | {
"start": 1211,
"end": 1408
} | class ____ {
@Private
@Unstable
public static ReInitializeContainerResponse newInstance() {
return Records.newRecord(ReInitializeContainerResponse.class);
}
}
| ReInitializeContainerResponse |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/antora/CheckJavadocMacros.java | {
"start": 9718,
"end": 10264
} | class ____ {
private final Origin origin;
protected JavadocAnchor(Origin origin) {
this.origin = origin;
}
Origin origin() {
return this.origin;
}
private static JavadocAnchor of(String anchor, Origin origin) {
JavadocAnchor javadocAnchor = WellKnownAnchor.of(anchor, origin);
if (javadocAnchor == null) {
javadocAnchor = MethodAnchor.of(anchor, origin);
}
if (javadocAnchor == null) {
javadocAnchor = FieldAnchor.of(anchor, origin);
}
return javadocAnchor;
}
}
private static final | JavadocAnchor |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DirectInvocationOnMockTest.java | {
"start": 8054,
"end": 8751
} | class ____ {
public <T> OngoingStubbing<T> when(T t) {
return org.mockito.Mockito.when(t);
}
public Object test() {
Test test = mock(Test.class);
when(test.test()).thenReturn(null);
return null;
}
}
""")
.doTest();
}
@Test
public void directInvocationOnMock_withinCustomGiven_noFinding() {
assumeTrue(isBddMockitoAvailable());
helper
.addSourceLines(
"Test.java",
"""
import static org.mockito.Mockito.mock;
import org.mockito.BDDMockito.BDDMyOngoingStubbing;
| Test |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectCheckerTest.java | {
"start": 5470,
"end": 6183
} | class ____
extends ArgumentSelectionDefectChecker {
public ArgumentSelectionDefectWithIgnoredFormalsHeuristic() {
super(
ArgumentChangeFinder.builder()
.setDistanceFunction(buildEqualityFunction())
.addHeuristic(new LowInformationNameHeuristic(ImmutableSet.of("ignore")))
.build());
}
}
@Test
public void argumentSelectionDefectChecker_rejectsSwap_withIgnoredFormalParameter() {
CompilationTestHelper.newInstance(
ArgumentSelectionDefectWithIgnoredFormalsHeuristic.class, getClass())
.addSourceLines(
"Test.java",
"""
abstract | ArgumentSelectionDefectWithIgnoredFormalsHeuristic |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/SequenceInformationExtractorH2DatabaseImpl.java | {
"start": 188,
"end": 685
} | class ____ extends SequenceInformationExtractorLegacyImpl {
/**
* Singleton access
*/
public static final SequenceInformationExtractorH2DatabaseImpl INSTANCE = new SequenceInformationExtractorH2DatabaseImpl();
@Override
protected String sequenceStartValueColumn() {
return null;
}
@Override
protected String sequenceMinValueColumn() {
return "min_value";
}
@Override
protected String sequenceMaxValueColumn() {
return "max_value";
}
}
| SequenceInformationExtractorH2DatabaseImpl |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/action/DelegatePkiAuthenticationResponseTests.java | {
"start": 1402,
"end": 6862
} | class ____ extends AbstractXContentTestCase<DelegatePkiAuthenticationResponse> {
public void testSerialization() throws Exception {
DelegatePkiAuthenticationResponse response = createTestInstance();
try (BytesStreamOutput output = new BytesStreamOutput()) {
response.writeTo(output);
try (StreamInput input = output.bytes().streamInput()) {
DelegatePkiAuthenticationResponse serialized = new DelegatePkiAuthenticationResponse(input);
assertThat(response.getAccessToken(), is(serialized.getAccessToken()));
assertThat(response.getExpiresIn(), is(serialized.getExpiresIn()));
assertThat(response.getAuthentication(), is(serialized.getAuthentication()));
assertThat(response, is(serialized));
}
}
}
@Override
protected DelegatePkiAuthenticationResponse createTestInstance() {
return new DelegatePkiAuthenticationResponse(
randomAlphaOfLengthBetween(0, 10),
randomTimeValue(),
builder().realm().realmRef(new RealmRef(randomAlphaOfLengthBetween(3, 8), TYPE, "node_name")).build(false)
);
}
@Override
protected DelegatePkiAuthenticationResponse doParseInstance(XContentParser parser) throws IOException {
return DelegatePkiAuthenticationResponseTests.PARSER.apply(parser, null);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
private static final ParseField ACCESS_TOKEN_FIELD = new ParseField("access_token");
private static final ParseField TYPE_FIELD = new ParseField("type");
private static final ParseField EXPIRES_IN_FIELD = new ParseField("expires_in");
private static final ParseField AUTHENTICATION = new ParseField("authentication");
public static final ConstructingObjectParser<DelegatePkiAuthenticationResponse, Void> PARSER = new ConstructingObjectParser<>(
"delegate_pki_response",
true,
a -> {
final String accessToken = (String) a[0];
final String type = (String) a[1];
if (false == "Bearer".equals(type)) {
throw new IllegalArgumentException("Unknown token type [" + type + "], only [Bearer] type permitted");
}
final Long expiresIn = (Long) a[2];
final Authentication authentication = (Authentication) a[3];
return new DelegatePkiAuthenticationResponse(accessToken, TimeValue.timeValueSeconds(expiresIn), authentication);
}
);
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), ACCESS_TOKEN_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), TYPE_FIELD);
PARSER.declareLong(ConstructingObjectParser.constructorArg(), EXPIRES_IN_FIELD);
PARSER.declareObject(optionalConstructorArg(), (p, c) -> parseAuthentication(p), AUTHENTICATION);
}
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<Authentication, Void> AUTH_PARSER = new ConstructingObjectParser<>(
"authentication",
true,
a -> {
// No lookup realm
assertThat(a[6], equalTo(a[7]));
assertThat(a[8], equalTo("realm"));
return Authentication.newRealmAuthentication(
new User(
(String) a[0],
((ArrayList<String>) a[1]).toArray(new String[0]),
(String) a[2],
(String) a[3],
(Map<String, Object>) a[4],
(boolean) a[5]
),
(Authentication.RealmRef) a[6]
);
}
);
static {
final ConstructingObjectParser<Authentication.RealmRef, Void> realmInfoParser = new ConstructingObjectParser<>(
"realm_info",
true,
a -> new Authentication.RealmRef((String) a[0], (String) a[1], "node_name")
);
realmInfoParser.declareString(ConstructingObjectParser.constructorArg(), User.Fields.REALM_NAME);
realmInfoParser.declareString(ConstructingObjectParser.constructorArg(), User.Fields.REALM_TYPE);
AUTH_PARSER.declareString(ConstructingObjectParser.constructorArg(), User.Fields.USERNAME);
AUTH_PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), User.Fields.ROLES);
AUTH_PARSER.declareStringOrNull(ConstructingObjectParser.optionalConstructorArg(), User.Fields.FULL_NAME);
AUTH_PARSER.declareStringOrNull(ConstructingObjectParser.optionalConstructorArg(), User.Fields.EMAIL);
AUTH_PARSER.declareObject(ConstructingObjectParser.constructorArg(), (parser, c) -> parser.map(), User.Fields.METADATA);
AUTH_PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), User.Fields.ENABLED);
AUTH_PARSER.declareObject(ConstructingObjectParser.constructorArg(), realmInfoParser, User.Fields.AUTHENTICATION_REALM);
AUTH_PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), realmInfoParser, User.Fields.LOOKUP_REALM);
AUTH_PARSER.declareString(ConstructingObjectParser.constructorArg(), User.Fields.AUTHENTICATION_TYPE);
}
public static Authentication parseAuthentication(final XContentParser parser) throws IOException {
return AUTH_PARSER.apply(parser, null);
}
}
| DelegatePkiAuthenticationResponseTests |
java | apache__avro | lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java | {
"start": 31800,
"end": 32887
} | class ____ extends BasicTest {
Rec[] sourceData = null;
public RecordTest() throws IOException {
this("Record");
}
public RecordTest(String name) throws IOException {
super(name, RECORD_SCHEMA, 6);
}
@Override
void genSourceData() {
Random r = newRandom();
sourceData = new Rec[count];
for (int i = 0; i < sourceData.length; i++) {
sourceData[i] = new Rec(r);
}
}
@Override
void readInternal(Decoder d) throws IOException {
for (int i = 0; i < count; i++) {
d.readDouble();
d.readDouble();
d.readDouble();
d.readInt();
d.readInt();
d.readInt();
}
}
@Override
void writeInternal(Encoder e) throws IOException {
for (Rec r : sourceData) {
e.writeDouble(r.f1);
e.writeDouble(r.f2);
e.writeDouble(r.f3);
e.writeInt(r.f4);
e.writeInt(r.f5);
e.writeInt(r.f6);
}
}
@Override
void reset() {
sourceData = null;
data = null;
}
}
static | RecordTest |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/endpoints/InvalidPathParamTest.java | {
"start": 837,
"end": 930
} | class ____ {
@OnOpen
public void onOpen() {
}
}
}
| InvalidPathParam |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AStorageClass.java | {
"start": 2547,
"end": 3332
} | class ____ works with all of them.
*/
public static Collection<Object[]> params() {
return Arrays.asList(new Object[][]{
{FAST_UPLOAD_BUFFER_DISK},
{FAST_UPLOAD_BUFFER_ARRAY}
});
}
private final String fastUploadBufferType;
public ITestS3AStorageClass(String fastUploadBufferType) {
this.fastUploadBufferType = fastUploadBufferType;
}
@Override
protected Configuration createConfiguration() {
Configuration conf = super.createConfiguration();
skipIfStorageClassTestsDisabled(conf);
disableFilesystemCaching(conf);
removeBaseAndBucketOverrides(conf, STORAGE_CLASS, FAST_UPLOAD_BUFFER);
conf.set(FAST_UPLOAD_BUFFER, fastUploadBufferType);
return conf;
}
/*
* This test ensures the default storage | configuration |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelDoOnNextTry.java | {
"start": 2682,
"end": 5757
} | class ____<T> implements ConditionalSubscriber<T>, Subscription {
final Subscriber<? super T> downstream;
final Consumer<? super T> onNext;
final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler;
Subscription upstream;
boolean done;
ParallelDoOnNextSubscriber(Subscriber<? super T> actual, Consumer<? super T> onNext,
BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) {
this.downstream = actual;
this.onNext = onNext;
this.errorHandler = errorHandler;
}
@Override
public void request(long n) {
upstream.request(n);
}
@Override
public void cancel() {
upstream.cancel();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (!tryOnNext(t)) {
upstream.request(1);
}
}
@Override
public boolean tryOnNext(T t) {
if (done) {
return false;
}
long retries = 0;
for (;;) {
try {
onNext.accept(t);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
ParallelFailureHandling h;
try {
h = Objects.requireNonNull(errorHandler.apply(++retries, ex), "The errorHandler returned a null ParallelFailureHandling");
} catch (Throwable exc) {
Exceptions.throwIfFatal(exc);
cancel();
onError(new CompositeException(ex, exc));
return false;
}
switch (h) {
case RETRY:
continue;
case SKIP:
return false;
case STOP:
cancel();
onComplete();
return false;
default:
cancel();
onError(ex);
return false;
}
}
downstream.onNext(t);
return true;
}
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
downstream.onComplete();
}
}
static final | ParallelDoOnNextSubscriber |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/CreationTimestampTest.java | {
"start": 945,
"end": 4635
} | class ____ {
@Id
@GeneratedValue
private Long id;
@Column(name = "`date`")
@CreationTimestamp
private Date date;
@Column(name = "`calendar`")
@CreationTimestamp
private Calendar calendar;
@Column(name = "`sqlDate`")
@CreationTimestamp
private java.sql.Date sqlDate;
@Column(name = "`time`")
@CreationTimestamp
private Time time;
@Column(name = "`timestamp`")
@CreationTimestamp
private Timestamp timestamp;
@Column(name = "`instant`")
@CreationTimestamp
private Instant instant;
@Column(name = "`localDate`")
@CreationTimestamp
private LocalDate localDate;
@Column(name = "`localDateTime`")
@CreationTimestamp
private LocalDateTime localDateTime;
@Column(name = "`localTime`")
@CreationTimestamp
private LocalTime localTime;
@Column(name = "`monthDay`")
@CreationTimestamp
private MonthDay monthDay;
@Column(name = "`offsetDateTime`")
@CreationTimestamp
private OffsetDateTime offsetDateTime;
@Column(name = "`offsetTime`")
@CreationTimestamp
private OffsetTime offsetTime;
@Column(name = "`year`")
@CreationTimestamp
private Year year;
@Column(name = "`yearMonth`")
@CreationTimestamp
private YearMonth yearMonth;
@Column(name = "`zonedDateTime`")
@CreationTimestamp
private ZonedDateTime zonedDateTime;
public Event() {
}
public Long getId() {
return id;
}
public Date getDate() {
return date;
}
public Calendar getCalendar() {
return calendar;
}
public java.sql.Date getSqlDate() {
return sqlDate;
}
public Time getTime() {
return time;
}
public Timestamp getTimestamp() {
return timestamp;
}
public Instant getInstant() {
return instant;
}
public LocalDate getLocalDate() {
return localDate;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public LocalTime getLocalTime() {
return localTime;
}
public MonthDay getMonthDay() {
return monthDay;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public Year getYear() {
return year;
}
public YearMonth getYearMonth() {
return yearMonth;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
}
@Test
public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Event event = new Event();
entityManager.persist(event);
entityManager.flush();
check( event );
});
}
@Test
@JiraKey( value = "HHH-16240")
public void generatesCurrentTimestampInStatelessSession(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Session session = entityManager.unwrap( Session.class);
try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) {
Event event = new Event();
statelessSession.getTransaction().begin();
statelessSession.insert(event);
statelessSession.getTransaction().commit();
check( event );
}
});
}
private void check(Event event) {
assertNotNull(event.getDate());
assertNotNull(event.getCalendar());
assertNotNull(event.getSqlDate());
assertNotNull(event.getTime());
assertNotNull(event.getTimestamp());
assertNotNull(event.getInstant());
assertNotNull(event.getLocalDate());
assertNotNull(event.getLocalDateTime());
assertNotNull(event.getLocalTime());
assertNotNull(event.getMonthDay());
assertNotNull(event.getOffsetDateTime());
assertNotNull(event.getOffsetTime());
assertNotNull(event.getYear());
assertNotNull(event.getYearMonth());
assertNotNull(event.getZonedDateTime());
}
}
| Event |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/DefaultLayoutTest.java | {
"start": 1191,
"end": 2107
} | class ____ {
@Test
void testDefaultLayout() {
PrintStream standardOutput = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
try {
Logger log = LogManager.getLogger(getClass());
log.fatal("This is a fatal message");
log.error("This is an error message");
log.warn("This is a warning message");
String actualOutput = new String(baos.toByteArray(), Charset.defaultCharset());
assertTrue(actualOutput.contains("FATAL This is a fatal message" + System.lineSeparator()));
assertTrue(actualOutput.contains("ERROR This is an error message" + System.lineSeparator()));
assertFalse(actualOutput.contains("This is a warning message"));
} finally {
System.setOut(standardOutput);
}
}
}
| DefaultLayoutTest |
java | quarkusio__quarkus | extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/TransactionConfiguration.java | {
"start": 816,
"end": 2048
} | interface ____ {
/**
* This value is used to specify that no transaction timeout is configured.
*/
int UNSET_TIMEOUT = -1;
/**
* The transaction timeout in seconds.
* Defaults to UNSET_TIMEOUT: no timeout configured.
*
* @return The transaction timeout in seconds.
*/
int timeout() default UNSET_TIMEOUT;
String UNSET_TIMEOUT_CONFIG_PROPERTY = "<<unset>>";
/**
* The configuration property to use in order to determine the value of the timeout in seconds.
* If the property exists, it must be an integer value representing the transaction timeout in seconds.
*
* An example configuration in {@code application.properties} could be: {@code my-transaction.timeout=5}.
*
* If both {@code timeoutFromConfigProperty} and {@code timeout} are set, then Quarkus will attempt to resolve
* {@code timeoutFromConfigProperty} and if a value for it has been provided, the timeout is set to that value.
* If no value has been provided at runtime for the property, then the value of {@code timeout} will be used
* as the fallback.
*/
String timeoutFromConfigProperty() default UNSET_TIMEOUT_CONFIG_PROPERTY;
}
| TransactionConfiguration |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/convertor/BitsSizeReplayConvertor.java | {
"start": 708,
"end": 924
} | class ____ implements Convertor<Long> {
@Override
public Long convert(Object obj) {
if (obj == null) {
return null;
}
return ((Long) obj) * 8;
}
}
| BitsSizeReplayConvertor |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RecipientListThrowExceptionFromExpressionTest.java | {
"start": 1097,
"end": 2148
} | class ____ extends ContextTestSupport {
@Test
public void testRecipientListAndVerifyException() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(ExpressionEvaluationException.class).handled(true).to("mock://error");
from("direct://start").to("log:foo").recipientList()
.method(RecipientListThrowExceptionFromExpressionTest.class, "sendTo").to("mock://result").end();
}
};
}
public List<String> sendTo(Exchange exchange) throws ExpressionEvaluationException {
throw new ExpressionEvaluationException(null, exchange, null);
}
}
| RecipientListThrowExceptionFromExpressionTest |
java | spring-projects__spring-boot | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java | {
"start": 14032,
"end": 14839
} | enum ____ {
/**
* Content from a standard zip file.
*/
ZIP,
/**
* Content from nested zip content.
*/
NESTED_ZIP,
/**
* Content from a nested zip directory.
*/
NESTED_DIRECTORY
}
/**
* The source of {@link ZipContent}. Used as a cache key.
*
* @param path the path of the zip or container zip
* @param nestedEntryName the name of the nested entry to use or {@code null}
*/
private record Source(Path path, String nestedEntryName) {
/**
* Return if this is the source of a nested zip.
* @return if this is for a nested zip
*/
boolean isNested() {
return this.nestedEntryName != null;
}
@Override
public String toString() {
return (!isNested()) ? path().toString() : path() + "[" + nestedEntryName() + "]";
}
}
/**
* Internal | Kind |
java | apache__dubbo | dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java | {
"start": 1666,
"end": 6174
} | class ____ extends AbstractAnnotationProcessingTest {
private SimpleTypeDefinitionBuilder builder;
private VariableElement vField;
private VariableElement zField;
private VariableElement cField;
private VariableElement bField;
private VariableElement sField;
private VariableElement iField;
private VariableElement lField;
private VariableElement fField;
private VariableElement dField;
private VariableElement strField;
private VariableElement bdField;
private VariableElement biField;
private VariableElement dtField;
private VariableElement invalidField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(SimpleTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new SimpleTypeDefinitionBuilder();
TypeElement testType = getType(SimpleTypeModel.class);
vField = findField(testType, "v");
zField = findField(testType, "z");
cField = findField(testType, "c");
bField = findField(testType, "b");
sField = findField(testType, "s");
iField = findField(testType, "i");
lField = findField(testType, "l");
fField = findField(testType, "f");
dField = findField(testType, "d");
strField = findField(testType, "str");
bdField = findField(testType, "bd");
biField = findField(testType, "bi");
dtField = findField(testType, "dt");
invalidField = findField(testType, "invalid");
assertEquals("java.lang.Void", vField.asType().toString());
assertEquals("java.lang.Boolean", zField.asType().toString());
assertEquals("java.lang.Character", cField.asType().toString());
assertEquals("java.lang.Byte", bField.asType().toString());
assertEquals("java.lang.Short", sField.asType().toString());
assertEquals("java.lang.Integer", iField.asType().toString());
assertEquals("java.lang.Long", lField.asType().toString());
assertEquals("java.lang.Float", fField.asType().toString());
assertEquals("java.lang.Double", dField.asType().toString());
assertEquals("java.lang.String", strField.asType().toString());
assertEquals("java.math.BigDecimal", bdField.asType().toString());
assertEquals("java.math.BigInteger", biField.asType().toString());
assertEquals("java.util.Date", dtField.asType().toString());
assertEquals("int", invalidField.asType().toString());
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, vField.asType()));
assertTrue(builder.accept(processingEnv, zField.asType()));
assertTrue(builder.accept(processingEnv, cField.asType()));
assertTrue(builder.accept(processingEnv, bField.asType()));
assertTrue(builder.accept(processingEnv, sField.asType()));
assertTrue(builder.accept(processingEnv, iField.asType()));
assertTrue(builder.accept(processingEnv, lField.asType()));
assertTrue(builder.accept(processingEnv, fField.asType()));
assertTrue(builder.accept(processingEnv, dField.asType()));
assertTrue(builder.accept(processingEnv, strField.asType()));
assertTrue(builder.accept(processingEnv, bdField.asType()));
assertTrue(builder.accept(processingEnv, biField.asType()));
assertTrue(builder.accept(processingEnv, dtField.asType()));
// false condition
assertFalse(builder.accept(processingEnv, invalidField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, vField, builder);
buildAndAssertTypeDefinition(processingEnv, zField, builder);
buildAndAssertTypeDefinition(processingEnv, cField, builder);
buildAndAssertTypeDefinition(processingEnv, sField, builder);
buildAndAssertTypeDefinition(processingEnv, iField, builder);
buildAndAssertTypeDefinition(processingEnv, lField, builder);
buildAndAssertTypeDefinition(processingEnv, fField, builder);
buildAndAssertTypeDefinition(processingEnv, dField, builder);
buildAndAssertTypeDefinition(processingEnv, strField, builder);
buildAndAssertTypeDefinition(processingEnv, bdField, builder);
buildAndAssertTypeDefinition(processingEnv, biField, builder);
buildAndAssertTypeDefinition(processingEnv, dtField, builder);
}
}
| SimpleTypeDefinitionBuilderTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToManyCollectionCacheEvictionTest.java | {
"start": 2758,
"end": 3054
} | class ____ {
@Id
@GeneratedValue
private Integer id;
@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<Application> applications = new ArrayList<Application>();
}
@Entity(name = "Application")
@Table(name = "application")
@Cacheable
public static | Customer |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/packagescan/classreading/ClassReader.java | {
"start": 30017,
"end": 30659
} | class ____ or
* adapters.</i>
*
* @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose
* value is the index of a CONSTANT_Package entry in class's constant pool table.
* @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently
* large. It is not automatically resized.
* @return the String corresponding to the specified CONSTANT_Package entry.
*/
public String readPackage(final int offset, final char[] charBuffer) {
return readStringish(offset, charBuffer);
}
}
| generators |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/image/ClientQuotasDelta.java | {
"start": 1095,
"end": 3621
} | class ____ {
private final ClientQuotasImage image;
private final Map<ClientQuotaEntity, ClientQuotaDelta> changes = new HashMap<>();
public ClientQuotasDelta(ClientQuotasImage image) {
this.image = image;
}
public Map<ClientQuotaEntity, ClientQuotaDelta> changes() {
return changes;
}
public void finishSnapshot() {
for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : image.entities().entrySet()) {
ClientQuotaEntity entity = entry.getKey();
ClientQuotaImage quotaImage = entry.getValue();
ClientQuotaDelta quotaDelta = changes.computeIfAbsent(entity,
__ -> new ClientQuotaDelta(quotaImage));
quotaDelta.finishSnapshot();
}
}
public void handleMetadataVersionChange(MetadataVersion newVersion) {
// no-op
}
public void replay(ClientQuotaRecord record) {
ClientQuotaEntity entity = ClientQuotaImage.dataToEntity(record.entity());
ClientQuotaDelta change = changes.computeIfAbsent(entity, __ ->
new ClientQuotaDelta(image.entities().
getOrDefault(entity, ClientQuotaImage.EMPTY)));
change.replay(record);
}
public ClientQuotasImage apply() {
Map<ClientQuotaEntity, ClientQuotaImage> newEntities =
new HashMap<>(image.entities().size());
for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : image.entities().entrySet()) {
ClientQuotaEntity entity = entry.getKey();
ClientQuotaDelta change = changes.get(entity);
if (change == null) {
newEntities.put(entity, entry.getValue());
} else {
ClientQuotaImage quotaImage = change.apply();
if (!quotaImage.isEmpty()) {
newEntities.put(entity, quotaImage);
}
}
}
for (Entry<ClientQuotaEntity, ClientQuotaDelta> entry : changes.entrySet()) {
ClientQuotaEntity entity = entry.getKey();
if (!newEntities.containsKey(entity)) {
ClientQuotaImage quotaImage = entry.getValue().apply();
if (!quotaImage.isEmpty()) {
newEntities.put(entity, quotaImage);
}
}
}
return new ClientQuotasImage(newEntities);
}
@Override
public String toString() {
return "ClientQuotasDelta(" +
"changes=" + changes +
')';
}
}
| ClientQuotasDelta |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/tck/DoFinallyTckTest.java | {
"start": 830,
"end": 1074
} | class ____ extends BaseTck<Integer> {
@Override
public Publisher<Integer> createPublisher(long elements) {
return
Flowable.range(0, (int)elements).doFinally(Functions.EMPTY_ACTION)
;
}
}
| DoFinallyTckTest |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java | {
"start": 23553,
"end": 23807
} | class ____ {
private List<Integer> list = new ArrayList<>();
public List<Integer> getList() {
return list;
}
public void setList(List<Integer> list) {
this.list = list;
}
}
@SuppressWarnings("unused")
private static | IntegerListHolder1 |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrail.java | {
"start": 102322,
"end": 104657
} | class ____ {
private volatile Map<String, EventFilterPolicy> policyMap;
private volatile Predicate<AuditEventMetaInfo> predicate;
private EventFilterPolicyRegistry(Settings settings) {
final var entries = new ArrayList<Map.Entry<String, EventFilterPolicy>>();
for (final String policyName : settings.getGroups(FILTER_POLICY_PREFIX, true).keySet()) {
entries.add(entry(policyName, new EventFilterPolicy(policyName, settings)));
}
policyMap = Maps.ofEntries(entries);
// precompute predicate
predicate = buildIgnorePredicate(policyMap);
}
private synchronized void set(String policyName, EventFilterPolicy eventFilterPolicy) {
policyMap = Maps.copyMapWithAddedOrReplacedEntry(policyMap, policyName, eventFilterPolicy);
// precompute predicate
predicate = buildIgnorePredicate(policyMap);
}
private synchronized void remove(String policyName) {
policyMap = Maps.copyMapWithRemovedEntry(policyMap, policyName);
// precompute predicate
predicate = buildIgnorePredicate(policyMap);
}
Predicate<AuditEventMetaInfo> ignorePredicate() {
return predicate;
}
private static Predicate<AuditEventMetaInfo> buildIgnorePredicate(Map<String, EventFilterPolicy> policyMap) {
return policyMap.values().stream().map(EventFilterPolicy::ignorePredicate).reduce(Predicates.never(), Predicate::or);
}
@Override
public String toString() {
final Map<String, EventFilterPolicy> treeMap = new TreeMap<>(policyMap);
final StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, EventFilterPolicy> entry : treeMap.entrySet()) {
sb.append(entry.getKey()).append(":").append(entry.getValue().toString());
}
return sb.toString();
}
}
/**
* Abstraction for the fields of the audit event that are used for filtering. If
* an event has a missing field (one of `user`, `realm`, `roles` and `indices`)
* the value for the field will be the empty string or a singleton stream of the
* empty string.
*/
static final | EventFilterPolicyRegistry |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java | {
"start": 7390,
"end": 7713
} | class ____ implements BeanDefinitionRegistryPostProcessor,
BeanRegistrationAotProcessor, BeanFactoryInitializationAotProcessor, PriorityOrdered,
ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
/**
* A {@code BeanNameGenerator} using fully qualified | ConfigurationClassPostProcessor |
java | google__guava | android/guava/src/com/google/common/util/concurrent/Monitor.java | {
"start": 1884,
"end": 4250
} | class ____ guarantee that only one thread is awakened when a
* condition becomes true (no "signaling storms" due to use of {@link
* java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
* (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
* Condition.signal}).
*
* <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet
* <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also
* reentrant, so a thread may enter a monitor any number of times, and then must leave the same
* number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization
* semantics as the built-in Java language synchronization primitives.
*
* <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be
* followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the
* monitor cleanly:
*
* {@snippet :
* monitor.enter();
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }
* }
*
* <p>A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear
* as the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that
* the current thread leaves the monitor cleanly:
*
* {@snippet :
* if (monitor.tryEnter()) {
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }
* } else {
* // do other things since the monitor was not available
* }
* }
*
* <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2>
*
* <p>The following examples show a simple threadsafe holder expressed using {@code synchronized},
* {@link ReentrantLock}, and {@code Monitor}.
*
* <h3>{@code synchronized}</h3>
*
* <p>This version is the fewest lines of code, largely because the synchronization mechanism used
* is built into the language and runtime. But the programmer has to remember to avoid a couple of
* common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
* {@code notifyAll()} must be used instead of {@code notify()} because there are two different
* logical conditions being awaited.
*
* {@snippet :
* public | can |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PutJobActionRequestTests.java | {
"start": 717,
"end": 1316
} | class ____ extends AbstractWireSerializingTestCase<Request> {
private final String jobId = randomValidJobId();
@Override
protected Request createTestInstance() {
Job.Builder jobConfiguration = buildJobBuilder(jobId, null);
return new Request(jobConfiguration);
}
@Override
protected Request mutateInstance(Request instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<Request> instanceReader() {
return Request::new;
}
}
| PutJobActionRequestTests |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/WebhookComponentBuilderFactory.java | {
"start": 1914,
"end": 7726
} | interface ____ extends ComponentBuilder<WebhookComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Automatically register the webhook at startup and unregister it on
* shutdown.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param webhookAutoRegister the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder webhookAutoRegister(boolean webhookAutoRegister) {
doSetProperty("webhookAutoRegister", webhookAutoRegister);
return this;
}
/**
* The first (base) path element where the webhook will be exposed. It's
* a good practice to set it to a random string, so that it cannot be
* guessed by unauthorized parties.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param webhookBasePath the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder webhookBasePath(java.lang.String webhookBasePath) {
doSetProperty("webhookBasePath", webhookBasePath);
return this;
}
/**
* The Camel Rest component to use for the REST transport, such as
* netty-http.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param webhookComponentName the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder webhookComponentName(java.lang.String webhookComponentName) {
doSetProperty("webhookComponentName", webhookComponentName);
return this;
}
/**
* The URL of the current service as seen by the webhook provider.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param webhookExternalUrl the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder webhookExternalUrl(java.lang.String webhookExternalUrl) {
doSetProperty("webhookExternalUrl", webhookExternalUrl);
return this;
}
/**
* The path where the webhook endpoint will be exposed (relative to
* basePath, if any).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param webhookPath the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder webhookPath(java.lang.String webhookPath) {
doSetProperty("webhookPath", webhookPath);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* Set the default configuration for the webhook meta-component.
*
* The option is a:
* <code>org.apache.camel.component.webhook.WebhookConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default WebhookComponentBuilder configuration(org.apache.camel.component.webhook.WebhookConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
}
| WebhookComponentBuilder |
java | apache__camel | core/camel-base/src/main/java/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.java | {
"start": 12424,
"end": 13579
} | class ____ defined
// in two different jars (as is the case sometimes with specs).
if (AnnotationHelper.hasAnnotation(method, Converter.class, true)) {
boolean allowNull = false;
if (method.getAnnotation(Converter.class) != null) {
allowNull = method.getAnnotation(Converter.class).allowNull();
}
boolean fallback = method.getAnnotation(Converter.class).fallback();
if (fallback) {
injector = handleHasFallbackConverterAnnotation(registry, type, injector, method, allowNull);
} else {
injector = handleHasConverterAnnotation(registry, type, injector, method, allowNull);
}
}
}
Class<?> superclass = type.getSuperclass();
if (superclass != null && !superclass.equals(Object.class)) {
loadConverterMethods(registry, superclass);
}
} catch (NoClassDefFoundError e) {
boolean ignore = false;
// does the | is |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.