language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/EffectivelyPrivateTest.java
|
{
"start": 825,
"end": 1115
}
|
class ____ {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(EffectivelyPrivate.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"""
|
EffectivelyPrivateTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/lib/MutableCounterInt.java
|
{
"start": 1251,
"end": 1932
}
|
class ____ extends MutableCounter {
private AtomicInteger value = new AtomicInteger();
MutableCounterInt(MetricsInfo info, int initValue) {
super(info);
this.value.set(initValue);
}
@Override
public void incr() {
incr(1);
}
/**
* Increment the value by a delta
* @param delta of the increment
*/
public synchronized void incr(int delta) {
value.addAndGet(delta);
setChanged();
}
public int value() {
return value.get();
}
@Override
public void snapshot(MetricsRecordBuilder builder, boolean all) {
if (all || changed()) {
builder.addCounter(info(), value());
clearChanged();
}
}
}
|
MutableCounterInt
|
java
|
quarkusio__quarkus
|
extensions/scheduler/runtime-dev/src/main/java/io/quarkus/scheduler/runtime/dev/ui/SchedulerJsonRPCService.java
|
{
"start": 11364,
"end": 12401
}
|
class ____ implements ScheduledExecution {
private final Instant now;
DevUIScheduledExecution() {
super();
this.now = Instant.now();
}
@Override
public Trigger getTrigger() {
return new Trigger() {
@Override
public String getId() {
return "dev-console";
}
@Override
public Instant getNextFireTime() {
return null;
}
@Override
public Instant getPreviousFireTime() {
return now;
}
@Override
public boolean isOverdue() {
return false;
}
};
}
@Override
public Instant getFireTime() {
return now;
}
@Override
public Instant getScheduledFireTime() {
return now;
}
}
}
|
DevUIScheduledExecution
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/categorization/GrokPatternCreator.java
|
{
"start": 964,
"end": 12645
}
|
class ____ {
private static final boolean ECS_COMPATIBILITY = true;
private static final Logger logger = LogManager.getLogger(GrokPatternCreator.class);
private static final String PREFACE = "preface";
private static final String EPILOGUE = "epilogue";
private static final int MAX_RECURSE_DEPTH = 10;
/**
* The first match in this list will be chosen, so it needs to be ordered
* such that more generic patterns come after more specific patterns.
*/
private static final List<GrokPatternCandidate> ORDERED_CANDIDATE_GROK_PATTERNS = Arrays.asList(
new GrokPatternCandidate("TOMCATLEGACY_DATESTAMP", "timestamp"),
new GrokPatternCandidate("TIMESTAMP_ISO8601", "timestamp"),
new GrokPatternCandidate("DATESTAMP_RFC822", "timestamp"),
new GrokPatternCandidate("DATESTAMP_RFC2822", "timestamp"),
new GrokPatternCandidate("DATESTAMP_OTHER", "timestamp"),
new GrokPatternCandidate("DATESTAMP_EVENTLOG", "timestamp"),
new GrokPatternCandidate("SYSLOGTIMESTAMP", "timestamp"),
new GrokPatternCandidate("HTTPDATE", "timestamp"),
new GrokPatternCandidate("CATALINA_DATESTAMP", "timestamp"),
new GrokPatternCandidate("CISCOTIMESTAMP", "timestamp"),
new GrokPatternCandidate("DATE", "date"),
new GrokPatternCandidate("TIME", "time"),
new GrokPatternCandidate("LOGLEVEL", "log.level"),
new GrokPatternCandidate("URI", "url.original"),
new GrokPatternCandidate("UUID", "uuid"),
new GrokPatternCandidate("MAC", "macaddress"),
// Can't use \b as the breaks, because slashes are not "word" characters
new GrokPatternCandidate("PATH", "path", "(?<!\\w)", "(?!\\w)"),
new GrokPatternCandidate("EMAILADDRESS", "email"),
// TODO: would be nice to have IPORHOST here, but HOST matches almost all words
new GrokPatternCandidate("IP", "ipaddress"),
// This already includes pre/post break conditions
new GrokPatternCandidate("QUOTEDSTRING", "field", "", ""),
// Disallow +, - and . before numbers, as well as "word" characters, otherwise we'll pick
// up numeric suffices too eagerly
new GrokPatternCandidate("NUMBER", "field", "(?<![\\w.+-])", "(?![\\w+-]|\\.\\d)"),
new GrokPatternCandidate("BASE16NUM", "field", "(?<![\\w.+-])", "(?![\\w+-]|\\.\\w)")
// TODO: also unfortunately can't have USERNAME in the list as it matches too broadly
// Fixing these problems with overly broad matches would require some extra intelligence
// to be added to remove inappropriate matches. One idea would be to use a dictionary,
// but that doesn't necessarily help as "jay" could be a username but is also a dictionary
// word (plus there's the international headache with relying on dictionaries). Similarly,
// hostnames could also be dictionary words - I've worked on machines called "hippo" and
// "scarf" in the past. Another idea would be to look at the adjacent characters and
// apply some heuristic based on those.
);
private GrokPatternCreator() {}
/**
* Given a category definition regex and a collection of examples from the category, return
* a grok pattern that will match the category and pull out any likely fields. The extracted
* fields are given pretty generic names, but unique within the grok pattern provided. The
* expectation is that a user will adjust the extracted field names based on their domain
* knowledge.
*/
public static String findBestGrokMatchFromExamples(String jobId, String regex, Collection<String> examples) {
// The first string in this array will end up being the empty string, and it doesn't correspond
// to an "in between" bit. Although it could be removed for "neatness", it actually makes the
// loops below slightly neater if it's left in.
//
// E.g., ".*?cat.+?sat.+?mat.*" -> [ "", "cat", "sat", "mat" ]
String[] fixedRegexBits = regex.split("\\.[*+]\\??");
// If there are no fixed regex bits, that implies there would only be a single capture group
// And that would mean a pretty uninteresting grok pattern
if (fixedRegexBits.length == 0) {
return regex;
}
// Create a pattern that will capture the bits in between the fixed parts of the regex
//
// E.g., ".*?cat.+?sat.+?mat.*" -> Pattern (.*?)cat(.+?)sat(.+?)mat(.*)
Pattern exampleProcessor = Pattern.compile(regex.replaceAll("(\\.[*+]\\??)", "($1)"), Pattern.DOTALL);
List<Collection<String>> groupsMatchesFromExamples = new ArrayList<>(fixedRegexBits.length);
for (int i = 0; i < fixedRegexBits.length; ++i) {
groupsMatchesFromExamples.add(new ArrayList<>(examples.size()));
}
for (String example : examples) {
Matcher matcher = exampleProcessor.matcher(example);
if (matcher.matches()) {
assert matcher.groupCount() == fixedRegexBits.length;
// E.g., if the input regex was ".*?cat.+?sat.+?mat.*" then the example
// "the cat sat on the mat" will result in "the ", " ", " on the ", and ""
// being added to the 4 "in between" collections in that order
for (int groupNum = 1; groupNum <= matcher.groupCount(); ++groupNum) {
groupsMatchesFromExamples.get(groupNum - 1).add(matcher.group(groupNum));
}
} else {
// If we get here it implies the original categorization has produced a
// regex that doesn't match one of the examples. This can happen when
// the message was very long, and the example was truncated. In this
// case we will have appended an ellipsis to indicate truncation.
assert example.endsWith("...") : exampleProcessor.pattern() + " did not match non-truncated example " + example;
if (example.endsWith("...")) {
logger.trace(() -> format("[%s] Pattern [%s] did not match truncated example", jobId, exampleProcessor.pattern()));
} else {
logger.warn("[{}] Pattern [{}] did not match non-truncated example [{}]", jobId, exampleProcessor.pattern(), example);
}
}
}
Map<String, Integer> fieldNameCountStore = new HashMap<>();
StringBuilder overallGrokPatternBuilder = new StringBuilder();
// Finally, for each collection of "in between" bits we look for the best Grok pattern and incorporate
// it into the overall Grok pattern that will match the each example in its entirety
for (int inBetweenBitNum = 0; inBetweenBitNum < groupsMatchesFromExamples.size(); ++inBetweenBitNum) {
// Remember (from the first comment in this method) that the first element in this array is
// always the empty string
overallGrokPatternBuilder.append(fixedRegexBits[inBetweenBitNum]);
appendBestGrokMatchForStrings(
jobId,
fieldNameCountStore,
overallGrokPatternBuilder,
inBetweenBitNum == 0,
inBetweenBitNum == fixedRegexBits.length - 1,
groupsMatchesFromExamples.get(inBetweenBitNum)
);
}
return overallGrokPatternBuilder.toString();
}
private static void appendBestGrokMatchForStrings(
String jobId,
Map<String, Integer> fieldNameCountStore,
StringBuilder overallGrokPatternBuilder,
boolean isFirst,
boolean isLast,
Collection<String> mustMatchStrings,
int numRecurse
) {
GrokPatternCandidate bestCandidate = null;
if (mustMatchStrings.isEmpty() == false) {
for (GrokPatternCandidate candidate : ORDERED_CANDIDATE_GROK_PATTERNS) {
if (mustMatchStrings.stream().allMatch(candidate.grok::match)) {
bestCandidate = candidate;
break;
}
}
}
if (bestCandidate == null || numRecurse >= MAX_RECURSE_DEPTH) {
if (bestCandidate != null) {
logger.warn("[{}] exited grok discovery early, reached max depth [{}]", jobId, MAX_RECURSE_DEPTH);
}
if (isLast) {
overallGrokPatternBuilder.append(".*");
} else if (isFirst || mustMatchStrings.stream().anyMatch(String::isEmpty)) {
overallGrokPatternBuilder.append(".*?");
} else {
overallGrokPatternBuilder.append(".+?");
}
} else {
Collection<String> prefaces = new ArrayList<>();
Collection<String> epilogues = new ArrayList<>();
populatePrefacesAndEpilogues(mustMatchStrings, bestCandidate.grok, prefaces, epilogues);
appendBestGrokMatchForStrings(jobId, fieldNameCountStore, overallGrokPatternBuilder, isFirst, false, prefaces, numRecurse + 1);
overallGrokPatternBuilder.append("%{")
.append(bestCandidate.grokPatternName)
.append(':')
.append(buildFieldName(fieldNameCountStore, bestCandidate.fieldName))
.append('}');
appendBestGrokMatchForStrings(jobId, fieldNameCountStore, overallGrokPatternBuilder, false, isLast, epilogues, numRecurse + 1);
}
}
/**
* Given a collection of strings, work out which (if any) of the grok patterns we're allowed
* to use matches it best. Then append the appropriate grok language to represent that finding
* onto the supplied string builder.
*/
static void appendBestGrokMatchForStrings(
String jobId,
Map<String, Integer> fieldNameCountStore,
StringBuilder overallGrokPatternBuilder,
boolean isFirst,
boolean isLast,
Collection<String> mustMatchStrings
) {
appendBestGrokMatchForStrings(jobId, fieldNameCountStore, overallGrokPatternBuilder, isFirst, isLast, mustMatchStrings, 0);
}
/**
* Given a collection of strings, and a grok pattern that matches some part of them all,
* return collections of the bits that come before (prefaces) and after (epilogues) the
* bit that matches.
*/
static void populatePrefacesAndEpilogues(
Collection<String> matchingStrings,
Grok grok,
Collection<String> prefaces,
Collection<String> epilogues
) {
for (String s : matchingStrings) {
Map<String, Object> captures = grok.captures(s);
// If the pattern doesn't match then captures will be null. But we expect this
// method to only be called after validating that the pattern does match.
assert captures != null;
prefaces.add(captures.getOrDefault(PREFACE, "").toString());
epilogues.add(captures.getOrDefault(EPILOGUE, "").toString());
}
}
/**
* The first time a particular field name is passed, simply return it.
* The second time return it with "2" appended.
* The third time return it with "3" appended.
* Etc.
*/
static String buildFieldName(Map<String, Integer> fieldNameCountStore, String fieldName) {
Integer numberSeen = fieldNameCountStore.compute(fieldName, (k, v) -> 1 + ((v == null) ? 0 : v));
if (numberSeen > 1) {
return fieldName + numberSeen;
} else {
return fieldName;
}
}
static
|
GrokPatternCreator
|
java
|
spring-projects__spring-boot
|
module/spring-boot-servlet/src/main/java/org/springframework/boot/servlet/filter/OrderedRequestContextFilter.java
|
{
"start": 906,
"end": 1312
}
|
class ____ extends RequestContextFilter implements OrderedFilter {
// Order defaults to after Spring Session filter
private int order = REQUEST_WRAPPER_FILTER_MAX_ORDER - 105;
@Override
public int getOrder() {
return this.order;
}
/**
* Set the order for this filter.
* @param order the order to set
*/
public void setOrder(int order) {
this.order = order;
}
}
|
OrderedRequestContextFilter
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestCheckRemoveZKNodeRMStateStore.java
|
{
"start": 4400,
"end": 4548
}
|
class ____ implements RMStateStoreHelper {
private TestZKRMStateStoreInternal store;
private String workingZnode;
|
TestZKRMStateStoreTester
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-testing/src/main/java/io/quarkus/devtools/testing/codestarts/QuarkusCodestartTest.java
|
{
"start": 8600,
"end": 9191
}
|
class ____ the snapshots in all the projects for the given
* language
*
* @param language the language to check
* @param className the full qualified className (using `org.acme.ClassName` also works, it will be replaced by the project
* package name)
* @return
* @throws Throwable
*/
public AbstractPathAssert<?> checkGeneratedSource(Language language, String className) throws Throwable {
return checkGeneratedSource("main", language, className);
}
/**
* It will validate (compare and check package name) the test
|
against
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NettyHttpEndpointBuilderFactory.java
|
{
"start": 27970,
"end": 28488
}
|
class ____ could be used to return an SSL Handler.
*
* The option is a: <code>io.netty.handler.ssl.SslHandler</code> type.
*
* Group: security
*
* @param sslHandler the value to set
* @return the dsl builder
*/
default NettyHttpEndpointConsumerBuilder sslHandler(io.netty.handler.ssl.SslHandler sslHandler) {
doSetProperty("sslHandler", sslHandler);
return this;
}
/**
* Reference to a
|
that
|
java
|
apache__camel
|
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/client/CompositeSObjectCollectionsApiClient.java
|
{
"start": 1498,
"end": 2824
}
|
interface ____<T> {
void onResponse(Optional<T> body, Map<String, String> headers, SalesforceException exception);
}
<T> void submitRetrieveCompositeCollections(
RetrieveSObjectCollectionsDto retrieveDto, Map<String, List<String>> headers,
ResponseCallback<List<T>> callback, String sObjectName,
Class<T> returnType)
throws SalesforceException;
void createCompositeCollections(
SObjectCollection collection, Map<String, List<String>> headers,
ResponseCallback<List<SaveSObjectResult>> callback)
throws SalesforceException;
void updateCompositeCollections(
SObjectCollection collection, Map<String, List<String>> headers,
ResponseCallback<List<SaveSObjectResult>> callback)
throws SalesforceException;
void upsertCompositeCollections(
SObjectCollection collection, Map<String, List<String>> headers,
ResponseCallback<List<UpsertSObjectResult>> callback, String sObjectName, String externalIdFieldName)
throws SalesforceException;
void submitDeleteCompositeCollections(
List<String> ids, Boolean allOrNone, Map<String, List<String>> headers,
ResponseCallback<List<DeleteSObjectResult>> callback);
}
|
ResponseCallback
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginDependenciesValidator.java
|
{
"start": 1211,
"end": 2101
}
|
class ____ implements MavenPluginDependenciesValidator {
protected final PluginValidationManager pluginValidationManager;
protected AbstractMavenPluginDependenciesValidator(PluginValidationManager pluginValidationManager) {
this.pluginValidationManager = requireNonNull(pluginValidationManager);
}
@Override
public void validate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {
if (artifactDescriptorResult.getDependencies() != null) {
doValidate(session, pluginArtifact, artifactDescriptorResult);
}
}
protected abstract void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult);
}
|
AbstractMavenPluginDependenciesValidator
|
java
|
jhy__jsoup
|
src/main/java/org/jsoup/helper/Re2jRegex.java
|
{
"start": 128,
"end": 1168
}
|
class ____ extends Regex {
private static final java.util.regex.Pattern unused = java.util.regex.Pattern.compile("");
private final com.google.re2j.Pattern re2jPattern;
private Re2jRegex(com.google.re2j.Pattern re2jPattern) {
super(unused);
this.re2jPattern = re2jPattern;
}
public static Regex compile(String regex) {
try {
return new Re2jRegex(com.google.re2j.Pattern.compile(regex));
} catch (RuntimeException e) {
throw new ValidationException("Pattern syntax error: " + e.getMessage());
} catch (OutOfMemoryError | StackOverflowError e) { // defensive check on regex to normalize exception
throw new ValidationException("Pattern complexity error: " + e.getMessage());
}
}
@Override
public Matcher matcher(CharSequence input) {
return new Re2jMatcher(re2jPattern.matcher(input));
}
@Override
public String toString() {
return re2jPattern.toString();
}
private static final
|
Re2jRegex
|
java
|
micronaut-projects__micronaut-core
|
context/src/main/java/io/micronaut/scheduling/executor/ExecutorSelector.java
|
{
"start": 926,
"end": 1630
}
|
interface ____ {
/**
* Select an {@link ExecutorService} for the given {@link MethodReference}.
*
* @param method The {@link MethodReference}
* @param threadSelection The thread selection mode
* @return An optional {@link ExecutorService}. If an {@link ExecutorService} cannot be established
* {@link Optional#empty()} is returned
*/
Optional<ExecutorService> select(MethodReference<?, ?> method, ThreadSelection threadSelection);
/**
* Obtain executor for the given name.
* @param name The name of the executor
* @return An executor if it exists
* @since 3.1.0
*/
Optional<ExecutorService> select(String name);
}
|
ExecutorSelector
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/benckmark/sql/MySqlPerfMain_select.java
|
{
"start": 901,
"end": 2877
}
|
class ____ {
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
System.out.println(arguments);
String sql = "SELECT ID, NAME, AGE FROM USER WHERE ID = ?";
// String sql = "SELECT student_name, "
// + "GROUP_CONCAT(DISTINCT test_score "
// + " ORDER BY test_score DESC SEPARATOR ' ') "
// + "FROM student "
// + "GROUP BY student_name";
for (int i = 0; i < 10; ++i) {
perfMySql(sql); // 831 810
}
}
static long perfMySql(String sql) {
long startYGC = TestUtils.getYoungGC();
long startYGCTime = TestUtils.getYoungGCTime();
long startFGC = TestUtils.getFullGC();
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
execMySql(sql);
}
long millis = System.currentTimeMillis() - startMillis;
long ygc = TestUtils.getYoungGC() - startYGC;
long ygct = TestUtils.getYoungGCTime() - startYGCTime;
long fgc = TestUtils.getFullGC() - startFGC;
System.out.println("MySql\t" + millis + ", ygc " + ygc + ", ygct " + ygct + ", fgc " + fgc);
return millis;
}
static void execMySql(String sql) {
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
// StringBuilder out = new StringBuilder();
// MySqlOutputVisitor visitor = new MySqlOutputVisitor(out);
// MySqlASTVisitorAdapter visitor = new MySqlASTVisitorAdapter();
//
// for (SQLStatement statement : statementList) {
// statement.accept(visitor);
// }
// out.toString();
}
}
|
MySqlPerfMain_select
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLPartitionRef.java
|
{
"start": 1039,
"end": 2123
}
|
class ____ extends SQLObjectImpl {
private SQLIdentifierExpr columnName;
private SQLExpr value;
private SQLBinaryOperator operator;
public Item() {
}
public Item(SQLIdentifierExpr columnName) {
setColumnName(columnName);
}
@Override
protected void accept0(SQLASTVisitor v) {
}
public SQLIdentifierExpr getColumnName() {
return columnName;
}
public void setColumnName(SQLIdentifierExpr x) {
if (x != null) {
x.setParent(this);
}
this.columnName = x;
}
public SQLExpr getValue() {
return value;
}
public void setValue(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.value = x;
}
public SQLBinaryOperator getOperator() {
return operator;
}
public void setOperator(SQLBinaryOperator operator) {
this.operator = operator;
}
}
}
|
Item
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactoryTests.java
|
{
"start": 5625,
"end": 8968
}
|
class ____: [english, light_english]", e.getMessage());
}
public void testGermanAndGerman2Stemmer() throws IOException {
IndexVersion v = IndexVersionUtils.randomVersionBetween(random(), IndexVersions.UPGRADE_TO_LUCENE_10_0_0, IndexVersion.current());
Analyzer analyzer = createGermanStemmer("german", v);
assertAnalyzesTo(analyzer, "Buecher Bücher", new String[] { "Buch", "Buch" });
analyzer = createGermanStemmer("german2", v);
assertAnalyzesTo(analyzer, "Buecher Bücher", new String[] { "Buch", "Buch" });
assertWarnings(
"The 'german2' stemmer has been deprecated and folded into the 'german' Stemmer. "
+ "Replace all usages of 'german2' with 'german'."
);
}
private static Analyzer createGermanStemmer(String variant, IndexVersion v) throws IOException {
Settings settings = Settings.builder()
.put("index.analysis.filter.my_german.type", "stemmer")
.put("index.analysis.filter.my_german.language", variant)
.put("index.analysis.analyzer.my_german.tokenizer", "whitespace")
.put("index.analysis.analyzer.my_german.filter", "my_german")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_german");
assertThat(tokenFilter, instanceOf(StemmerTokenFilterFactory.class));
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader("Buecher oder Bücher"));
TokenStream create = tokenFilter.create(tokenizer);
assertThat(create, instanceOf(SnowballFilter.class));
IndexAnalyzers indexAnalyzers = analysis.indexAnalyzers;
NamedAnalyzer analyzer = indexAnalyzers.get("my_german");
return analyzer;
}
public void testKpDeprecation() throws IOException {
IndexVersion v = IndexVersionUtils.randomVersion();
Settings settings = Settings.builder()
.put("index.analysis.filter.my_kp.type", "stemmer")
.put("index.analysis.filter.my_kp.language", "kp")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN);
assertCriticalWarnings("The [dutch_kp] stemmer is deprecated and will be removed in a future version.");
}
public void testLovinsDeprecation() throws IOException {
IndexVersion v = IndexVersionUtils.randomVersion();
Settings settings = Settings.builder()
.put("index.analysis.filter.my_lovins.type", "stemmer")
.put("index.analysis.filter.my_lovins.language", "lovins")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN);
assertCriticalWarnings("The [lovins] stemmer is deprecated and will be removed in a future version.");
}
}
|
specified
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/state/StateSerializerProviderTest.java
|
{
"start": 15809,
"end": 16806
}
|
class ____
implements TypeSerializerSnapshot<String> {
@Override
public TypeSerializer<String> restoreSerializer() {
throw new UnsupportedOperationException();
}
@Override
public void writeSnapshot(DataOutputView out) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void readSnapshot(int readVersion, DataInputView in, ClassLoader userCodeClassLoader)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public TypeSerializerSchemaCompatibility<String> resolveSchemaCompatibility(
TypeSerializerSnapshot<String> oldSerializerSnapshot) {
throw new UnsupportedOperationException();
}
@Override
public int getCurrentVersion() {
throw new UnsupportedOperationException();
}
}
}
|
ExceptionThrowingSerializerSnapshot
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/DialectChecks.java
|
{
"start": 9079,
"end": 9388
}
|
class ____ implements DialectCheck {
public boolean isMatch(Dialect dialect) {
return dialect.supportsOrderByInSubquery()
// For some reason, HANA doesn't support order by in correlated subqueries...
&& !( dialect instanceof HANADialect );
}
}
public static
|
SupportsOrderByInCorrelatedSubquery
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBeforeOrEqualTo_Test.java
|
{
"start": 1236,
"end": 3607
}
|
class ____ extends OffsetTimeAssertBaseTest {
@Test
void test_isBeforeOrEqual_assertion() {
// WHEN
assertThat(BEFORE).isBeforeOrEqualTo(REFERENCE);
assertThat(BEFORE).isBeforeOrEqualTo(REFERENCE.toString());
assertThat(REFERENCE).isBeforeOrEqualTo(REFERENCE);
assertThat(REFERENCE).isBeforeOrEqualTo(REFERENCE.toString());
// THEN
verify_that_isBeforeOrEqual_assertion_fails_and_throws_AssertionError(AFTER, REFERENCE);
}
@Test
void test_isBeforeOrEqual_assertion_error_message() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(REFERENCE).isBeforeOrEqualTo(BEFORE))
.withMessage(shouldBeBeforeOrEqualTo(REFERENCE, BEFORE).create());
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
OffsetTime actual = null;
assertThat(actual).isBeforeOrEqualTo(OffsetTime.now());
}).withMessage(actualIsNull());
}
@Test
void should_fail_if_offsetTime_parameter_is_null() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetTime.now()).isBeforeOrEqualTo((OffsetTime) null))
.withMessage("The OffsetTime to compare actual with should not be null");
}
@Test
void should_fail_if_offsetTime_as_string_parameter_is_null() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetTime.now()).isBeforeOrEqualTo((String) null))
.withMessage("The String representing the OffsetTime to compare actual with should not be null");
}
private static void verify_that_isBeforeOrEqual_assertion_fails_and_throws_AssertionError(OffsetTime timeToCheck,
OffsetTime reference) {
try {
assertThat(timeToCheck).isBeforeOrEqualTo(reference);
} catch (AssertionError e) {
// AssertionError was expected, test same assertion with String based parameter
try {
assertThat(timeToCheck).isBeforeOrEqualTo(reference.toString());
} catch (AssertionError e2) {
// AssertionError was expected (again)
return;
}
}
fail("Should have thrown AssertionError");
}
}
|
OffsetTimeAssert_isBeforeOrEqualTo_Test
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/validatorfactory/ValidatorFactoryFromValidationCustomizerTest.java
|
{
"start": 529,
"end": 1146
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap
.create(JavaArchive.class)
.addClasses(MyMultipleValidatorFactoryCustomizer.class, MyEmailValidator.class,
MyNumValidator.class));
@Test
public void testOverrideConstraintValidatorConstraint() {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
assertThat(validatorFactory.getValidator().validate(new TestBean())).hasSize(2);
}
static
|
ValidatorFactoryFromValidationCustomizerTest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/io/checkpointing/AlignedCheckpointsMassiveRandomTest.java
|
{
"start": 5226,
"end": 5556
}
|
class ____ implements BarrierGenerator {
private final long every;
private long c = 0;
public CountBarrier(long every) {
this.every = every;
}
@Override
public boolean isNextBarrier() {
return c++ % every == 0;
}
}
private static
|
CountBarrier
|
java
|
spring-projects__spring-boot
|
module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityInterceptor.java
|
{
"start": 1791,
"end": 4794
}
|
class ____ {
private static final Log logger = LogFactory.getLog(SecurityInterceptor.class);
private final @Nullable TokenValidator tokenValidator;
private final @Nullable SecurityService cloudFoundrySecurityService;
private final @Nullable String applicationId;
private static final SecurityResponse SUCCESS = SecurityResponse.success();
SecurityInterceptor(@Nullable TokenValidator tokenValidator, @Nullable SecurityService cloudFoundrySecurityService,
@Nullable String applicationId) {
this.tokenValidator = tokenValidator;
this.cloudFoundrySecurityService = cloudFoundrySecurityService;
this.applicationId = applicationId;
}
SecurityResponse preHandle(HttpServletRequest request, @Nullable EndpointId endpointId) {
if (CorsUtils.isPreFlightRequest(request)) {
return SecurityResponse.success();
}
try {
if (!StringUtils.hasText(this.applicationId)) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Application id is not available");
}
if (this.cloudFoundrySecurityService == null || this.tokenValidator == null) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Cloud controller URL is not available");
}
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
return SUCCESS;
}
check(request, endpointId);
}
catch (Exception ex) {
logger.error(ex);
if (ex instanceof CloudFoundryAuthorizationException cfException) {
return new SecurityResponse(cfException.getStatusCode(),
"{\"security_error\":\"" + cfException.getMessage() + "\"}");
}
return new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
}
return SecurityResponse.success();
}
private void check(HttpServletRequest request, @Nullable EndpointId endpointId) {
Assert.state(this.cloudFoundrySecurityService != null, "'cloudFoundrySecurityService' must not be null");
Assert.state(this.applicationId != null, "'applicationId' must not be null");
Assert.state(this.tokenValidator != null, "'tokenValidator' must not be null");
Token token = getToken(request);
this.tokenValidator.validate(token);
AccessLevel accessLevel = this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId);
if (!accessLevel.isAccessAllowed((endpointId != null) ? endpointId.toLowerCaseString() : "")) {
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
}
request.setAttribute(AccessLevel.REQUEST_ATTRIBUTE, accessLevel);
}
private Token getToken(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
String bearerPrefix = "bearer ";
if (authorization == null || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) {
throw new CloudFoundryAuthorizationException(Reason.MISSING_AUTHORIZATION,
"Authorization header is missing or invalid");
}
return new Token(authorization.substring(bearerPrefix.length()));
}
}
|
SecurityInterceptor
|
java
|
playframework__playframework
|
documentation/manual/working/javaGuide/main/async/code/javaguide/async/MyWebSocketActor.java
|
{
"start": 233,
"end": 688
}
|
class ____ extends AbstractActor {
public static Props props(ActorRef out) {
return Props.create(MyWebSocketActor.class, out);
}
private final ActorRef out;
public MyWebSocketActor(ActorRef out) {
this.out = out;
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(String.class, message -> out.tell("I received your message: " + message, self()))
.build();
}
}
// #actor
|
MyWebSocketActor
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerParameterizedOutputVisitorTest_2.java
|
{
"start": 818,
"end": 1780
}
|
class ____ extends TestCase {
public void test_0() throws Exception {
String sql = "CREATE TABLE dbo.AO_B9A0F0_APPLIED_TEMPLATE ( ID INTEGER IDENTITY(1,1) NOT NULL, PROJECT_ID BIGINT CONSTRAINT df_AO_B9A0F0_APPLIED_TEMPLATE_PROJECT_ID DEFAULT 0, PROJECT_TEMPLATE_MODULE_KEY VARCHAR(255), PROJECT_TEMPLATE_WEB_ITEM_KEY VARCHAR(255), CONSTRAINT pk_AO_B9A0F0_APPLIED_TEMPLATE_ID PRIMARY KEY(ID) )";
assertEquals("CREATE TABLE dbo.AO_B9A0F0_APPLIED_TEMPLATE (\n" +
"\tID INTEGER DEFAULT NULL IDENTITY (1, 1),\n" +
"\tPROJECT_ID BIGINT DEFAULT 0,\n" +
"\tPROJECT_TEMPLATE_MODULE_KEY VARCHAR(255),\n" +
"\tPROJECT_TEMPLATE_WEB_ITEM_KEY VARCHAR(255),\n" +
"\tCONSTRAINT pk_AO_B9A0F0_APPLIED_TEMPLATE_ID PRIMARY KEY (ID)\n" +
")", ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.SQL_SERVER));
}
}
|
SQLServerParameterizedOutputVisitorTest_2
|
java
|
apache__flink
|
flink-python/src/test/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/stream/StreamArrowPythonRowTimeBoundedRangeOperatorTest.java
|
{
"start": 2878,
"end": 11547
}
|
class ____
extends AbstractStreamArrowPythonAggregateFunctionOperatorTest {
@Test
void testOverWindowAggregateFunction() throws Exception {
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
getTestHarness(new Configuration());
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
testHarness.processWatermark(Long.MAX_VALUE);
testHarness.close();
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 2L)));
expectedOutput.add(new Watermark(Long.MAX_VALUE));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
}
@Test
void testFinishBundleTriggeredOnWatermark() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
testHarness.processWatermark(new Watermark(10000L));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 2L)));
expectedOutput.add(new Watermark(10000L));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@Test
void testFinishBundleTriggeredByCount() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 4);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
assertOutputEquals(
"FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(1000L));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 2L)));
expectedOutput.add(new Watermark(1000L));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@Test
void testStateCleanup() throws Exception {
Configuration conf = new Configuration();
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
AbstractStreamOperator<RowData> operator = testHarness.getOperator();
testHarness.open();
AbstractKeyedStateBackend stateBackend =
(AbstractKeyedStateBackend) operator.getKeyedStateBackend();
assertThat(stateBackend.numKeyValueStateEntries())
.as("Initial state is not empty")
.isEqualTo(0);
testHarness.processElement(new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 100L)));
testHarness.processElement(new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 100L)));
testHarness.processElement(new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 500L)));
testHarness.processWatermark(new Watermark(1000L));
// at this moment we expect the function to have some records in state
testHarness.processWatermark(new Watermark(4000L));
// at this moment the function should have cleaned up states
assertThat(stateBackend.numKeyValueStateEntries())
.as("State has not been cleaned up")
.isEqualTo(0);
testHarness.close();
}
@Override
public LogicalType[] getOutputLogicalType() {
return new LogicalType[] {
DataTypes.STRING().getLogicalType(),
DataTypes.STRING().getLogicalType(),
DataTypes.BIGINT().getLogicalType(),
DataTypes.BIGINT().getLogicalType(),
DataTypes.BIGINT().getLogicalType()
};
}
@Override
public RowType getInputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new VarCharType()),
new RowType.RowField("f3", new BigIntType()),
new RowType.RowField("rowTime", new BigIntType())));
}
@Override
public RowType getOutputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new VarCharType()),
new RowType.RowField("f3", new BigIntType()),
new RowType.RowField("rowTime", new BigIntType()),
new RowType.RowField("agg", new BigIntType())));
}
@Override
public AbstractArrowPythonAggregateFunctionOperator getTestOperator(
Configuration config,
PythonFunctionInfo[] pandasAggregateFunctions,
RowType inputType,
RowType outputType,
int[] groupingSet,
int[] udafInputOffsets) {
RowType udfInputType = (RowType) Projection.of(udafInputOffsets).project(inputType);
RowType udfOutputType =
(RowType)
Projection.range(inputType.getFieldCount(), outputType.getFieldCount())
.project(outputType);
return new PassThroughStreamArrowPythonRowTimeBoundedRangeOperator(
config,
pandasAggregateFunctions,
inputType,
udfInputType,
udfOutputType,
3,
3L,
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(
new Configuration(),
Thread.currentThread().getContextClassLoader()),
"UdafInputProjection",
inputType,
udfInputType,
udafInputOffsets));
}
private static
|
StreamArrowPythonRowTimeBoundedRangeOperatorTest
|
java
|
quarkusio__quarkus
|
test-framework/junit5-component/src/test/java/io/quarkus/test/component/paraminject/ParameterInjectionParameterizedTest.java
|
{
"start": 560,
"end": 1009
}
|
class ____ {
@ParameterizedTest
@ValueSource(strings = { "alpha", "bravo", "delta" })
public void testParamsInjection(@SkipInject String param, Converter converter) {
Assertions.assertThat(converter.convert(param)).isIn("ALPHA", "BRAVO", "DELTA");
}
@AfterAll
public static void afterAll() {
assertEquals(3, Converter.DESTROYED.get());
}
@Dependent
public static
|
ParameterInjectionParameterizedTest
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/annotations/Options.java
|
{
"start": 1502,
"end": 1639
}
|
interface ____ {
/**
* The options for the {@link Options#flushCache()}. The default is {@link FlushCachePolicy#DEFAULT}
*/
|
Options
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/InconsistentCapitalizationTest.java
|
{
"start": 3273,
"end": 3353
}
|
class ____ {
Object aA;
C aB = new C();
void aA() {}
}
|
B
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/server/WebSession.java
|
{
"start": 1349,
"end": 5553
}
|
interface ____ {
/**
* Return a unique session identifier.
*/
String getId();
/**
* Return a map that holds session attributes.
*/
Map<String, Object> getAttributes();
/**
* Return the session attribute value if present.
* @param name the attribute name
* @param <T> the attribute type
* @return the attribute value
*/
@SuppressWarnings("unchecked")
default <T> @Nullable T getAttribute(String name) {
return (T) getAttributes().get(name);
}
/**
* Return the session attribute value or if not present raise an
* {@link IllegalArgumentException}.
* @param name the attribute name
* @param <T> the attribute type
* @return the attribute value
*/
@SuppressWarnings("unchecked")
default <T> T getRequiredAttribute(String name) {
T value = getAttribute(name);
Assert.notNull(value, () -> "Required attribute '" + name + "' is missing.");
return value;
}
/**
* Return the session attribute value, or a default, fallback value.
* @param name the attribute name
* @param defaultValue a default value to return instead
* @param <T> the attribute type
* @return the attribute value
*/
@SuppressWarnings("unchecked")
default <T> T getAttributeOrDefault(String name, T defaultValue) {
return (T) getAttributes().getOrDefault(name, defaultValue);
}
/**
* Force the creation of a session causing the session id to be sent when
* {@link #save()} is called.
*/
void start();
/**
* Whether a session with the client has been started explicitly via
* {@link #start()} or implicitly by adding session attributes.
* If "false" then the session id is not sent to the client and the
* {@link #save()} method is essentially a no-op.
*/
boolean isStarted();
/**
* Generate a new id for the session and update the underlying session
* storage to reflect the new id. After a successful call {@link #getId()}
* reflects the new session id.
* @return completion notification (success or error)
*/
Mono<Void> changeSessionId();
/**
* Invalidate the current session and clear session storage.
* @return completion notification (success or error)
*/
Mono<Void> invalidate();
/**
* Save the session through the {@code WebSessionStore} as follows:
* <ul>
* <li>If the session is new (i.e. created but never persisted), it must have
* been started explicitly via {@link #start()} or implicitly by adding
* attributes, or otherwise this method should have no effect.
* <li>If the session was retrieved through the {@code WebSessionStore},
* the implementation for this method must check whether the session was
* {@link #invalidate() invalidated} and if so return an error.
* </ul>
* <p>Note that this method is not intended for direct use by applications.
* Instead it is automatically invoked just before the response is
* committed.
* @return {@code Mono} to indicate completion with success or error
*/
Mono<Void> save();
/**
* Return {@code true} if the session expired after {@link #getMaxIdleTime()
* maxIdleTime} elapsed.
* <p>Typically expiration checks should be automatically made when a session
* is accessed, a new {@code WebSession} instance created if necessary, at
* the start of request processing so that applications don't have to worry
* about expired session by default.
*/
boolean isExpired();
/**
* Return the time when the session was created.
*/
Instant getCreationTime();
/**
* Return the last time of session access as a result of user activity such
* as an HTTP request. Together with {@link #getMaxIdleTime()
* maxIdleTimeInSeconds} this helps to determine when a session is
* {@link #isExpired() expired}.
*/
Instant getLastAccessTime();
/**
* Configure the max amount of time that may elapse after the
* {@link #getLastAccessTime() lastAccessTime} before a session is considered
* expired. A negative value indicates the session should not expire.
*/
void setMaxIdleTime(Duration maxIdleTime);
/**
* Return the maximum time after the {@link #getLastAccessTime()
* lastAccessTime} before a session expires. A negative time indicates the
* session doesn't expire.
*/
Duration getMaxIdleTime();
}
|
WebSession
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-testing/src/test/resources/__snapshots__/QuarkusJBangCodestartGenerationTest/generateDefaultProject/src_main.java
|
{
"start": 350,
"end": 524
}
|
class ____ {
@GET
public String sayHello() {
return "Hello RESTEasy";
}
public static void main(String[] args) {
Quarkus.run(args);
}
}
|
main
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/jobmanager/JobManagerProcessSpec.java
|
{
"start": 2558,
"end": 3851
}
|
class ____ extends CommonProcessMemorySpec<JobManagerFlinkMemory> {
private static final long serialVersionUID = 1L;
JobManagerProcessSpec(
JobManagerFlinkMemory flinkMemory, JvmMetaspaceAndOverhead jvmMetaspaceAndOverhead) {
super(flinkMemory, jvmMetaspaceAndOverhead);
}
@VisibleForTesting
public JobManagerProcessSpec(
MemorySize jvmHeapSize,
MemorySize offHeapSize,
MemorySize jvmMetaspaceSize,
MemorySize jvmOverheadSize) {
this(
new JobManagerFlinkMemory(jvmHeapSize, offHeapSize),
new JvmMetaspaceAndOverhead(jvmMetaspaceSize, jvmOverheadSize));
}
@Override
public String toString() {
return "JobManagerProcessSpec {"
+ "jvmHeapSize="
+ getJvmHeapMemorySize().toHumanReadableString()
+ ", "
+ "offHeapSize="
+ getJvmDirectMemorySize().toHumanReadableString()
+ ", "
+ "jvmMetaspaceSize="
+ getJvmMetaspaceSize().toHumanReadableString()
+ ", "
+ "jvmOverheadSize="
+ getJvmOverheadSize().toHumanReadableString()
+ '}';
}
}
|
JobManagerProcessSpec
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/util/concurrent/ExecutorThreadFactory.java
|
{
"start": 2020,
"end": 4953
}
|
class ____ implements ThreadFactory {
/** The thread pool name used when no explicit pool name has been specified. */
private static final String DEFAULT_POOL_NAME = "flink-executor-pool";
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final String namePrefix;
private final int threadPriority;
@Nullable private final UncaughtExceptionHandler exceptionHandler;
// ------------------------------------------------------------------------
/**
* Creates a new thread factory using the default thread pool name ('flink-executor-pool') and
* the default uncaught exception handler (log exception and kill process).
*/
public ExecutorThreadFactory() {
this(DEFAULT_POOL_NAME);
}
/**
* Creates a new thread factory using the given thread pool name and the default uncaught
* exception handler (log exception and kill process).
*
* @param poolName The pool name, used as the threads' name prefix
*/
public ExecutorThreadFactory(String poolName) {
this(poolName, FatalExitExceptionHandler.INSTANCE);
}
/**
* Creates a new thread factory using the given thread pool name and the given uncaught
* exception handler.
*
* @param poolName The pool name, used as the threads' name prefix
* @param exceptionHandler The uncaught exception handler for the threads
*/
public ExecutorThreadFactory(String poolName, UncaughtExceptionHandler exceptionHandler) {
this(poolName, Thread.NORM_PRIORITY, exceptionHandler);
}
ExecutorThreadFactory(
final String poolName,
final int threadPriority,
@Nullable final UncaughtExceptionHandler exceptionHandler) {
this.namePrefix = checkNotNull(poolName, "poolName") + "-thread-";
this.threadPriority = threadPriority;
this.exceptionHandler = exceptionHandler;
SecurityManager securityManager = System.getSecurityManager();
this.group =
(securityManager != null)
? securityManager.getThreadGroup()
: Thread.currentThread().getThreadGroup();
}
// ------------------------------------------------------------------------
@Override
public Thread newThread(Runnable runnable) {
Thread t = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement());
t.setDaemon(true);
t.setPriority(threadPriority);
// optional handler for uncaught exceptions
if (exceptionHandler != null) {
t.setUncaughtExceptionHandler(exceptionHandler);
}
return t;
}
// --------------------------------------------------------------------------------------------
/** Builder for {@link ExecutorThreadFactory}. */
public static final
|
ExecutorThreadFactory
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/producer/RoundRobinPartitioner.java
|
{
"start": 1386,
"end": 2935
}
|
class ____ implements Partitioner {
private final ConcurrentMap<String, AtomicInteger> topicCounterMap = new ConcurrentHashMap<>();
public void configure(Map<String, ?> configs) {}
/**
* Compute the partition for the given record.
*
* @param topic The topic name
* @param key The key to partition on (or null if no key)
* @param keyBytes serialized key to partition on (or null if no key)
* @param value The value to partition on or null
* @param valueBytes serialized value to partition on or null
* @param cluster The current cluster metadata
*/
@Override
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
int nextValue = nextValue(topic);
List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
if (!availablePartitions.isEmpty()) {
int part = Utils.toPositive(nextValue) % availablePartitions.size();
return availablePartitions.get(part).partition();
} else {
// no partitions are available, give a non-available partition
int numPartitions = cluster.partitionsForTopic(topic).size();
return Utils.toPositive(nextValue) % numPartitions;
}
}
private int nextValue(String topic) {
AtomicInteger counter = topicCounterMap.computeIfAbsent(topic, k -> new AtomicInteger(0));
return counter.getAndIncrement();
}
public void close() {}
}
|
RoundRobinPartitioner
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/OpensearchEndpointBuilderFactory.java
|
{
"start": 1571,
"end": 14253
}
|
interface ____
extends
EndpointProducerBuilder {
default AdvancedOpensearchEndpointBuilder advanced() {
return (AdvancedOpensearchEndpointBuilder) this;
}
/**
* The time in ms to wait before connection will time out.
*
* The option is a: <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param connectionTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder connectionTimeout(int connectionTimeout) {
doSetProperty("connectionTimeout", connectionTimeout);
return this;
}
/**
* The time in ms to wait before connection will time out.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param connectionTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder connectionTimeout(String connectionTimeout) {
doSetProperty("connectionTimeout", connectionTimeout);
return this;
}
/**
* Disconnect after it finish calling the producer.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param disconnect the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder disconnect(boolean disconnect) {
doSetProperty("disconnect", disconnect);
return this;
}
/**
* Disconnect after it finish calling the producer.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param disconnect the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder disconnect(String disconnect) {
doSetProperty("disconnect", disconnect);
return this;
}
/**
* Starting index of the response.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param from the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder from(Integer from) {
doSetProperty("from", from);
return this;
}
/**
* Starting index of the response.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: producer
*
* @param from the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder from(String from) {
doSetProperty("from", from);
return this;
}
/**
* Comma separated list with ip:port formatted remote transport
* addresses to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param hostAddresses the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder hostAddresses(String hostAddresses) {
doSetProperty("hostAddresses", hostAddresses);
return this;
}
/**
* The name of the index to act against.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param indexName the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder indexName(String indexName) {
doSetProperty("indexName", indexName);
return this;
}
/**
* The time in ms before retry.
*
* The option is a: <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param maxRetryTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder maxRetryTimeout(int maxRetryTimeout) {
doSetProperty("maxRetryTimeout", maxRetryTimeout);
return this;
}
/**
* The time in ms before retry.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param maxRetryTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder maxRetryTimeout(String maxRetryTimeout) {
doSetProperty("maxRetryTimeout", maxRetryTimeout);
return this;
}
/**
* What operation to perform.
*
* The option is a:
* <code>org.apache.camel.component.opensearch.OpensearchOperation</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder operation(org.apache.camel.component.opensearch.OpensearchOperation operation) {
doSetProperty("operation", operation);
return this;
}
/**
* What operation to perform.
*
* The option will be converted to a
* <code>org.apache.camel.component.opensearch.OpensearchOperation</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Time in ms during which OpenSearch will keep search context alive.
*
* The option is a: <code>int</code> type.
*
* Default: 60000
* Group: producer
*
* @param scrollKeepAliveMs the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder scrollKeepAliveMs(int scrollKeepAliveMs) {
doSetProperty("scrollKeepAliveMs", scrollKeepAliveMs);
return this;
}
/**
* Time in ms during which OpenSearch will keep search context alive.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 60000
* Group: producer
*
* @param scrollKeepAliveMs the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder scrollKeepAliveMs(String scrollKeepAliveMs) {
doSetProperty("scrollKeepAliveMs", scrollKeepAliveMs);
return this;
}
/**
* Size of the response.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param size the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder size(Integer size) {
doSetProperty("size", size);
return this;
}
/**
* Size of the response.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: producer
*
* @param size the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder size(String size) {
doSetProperty("size", size);
return this;
}
/**
* The timeout in ms to wait before the socket will time out.
*
* The option is a: <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param socketTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder socketTimeout(int socketTimeout) {
doSetProperty("socketTimeout", socketTimeout);
return this;
}
/**
* The timeout in ms to wait before the socket will time out.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 30000
* Group: producer
*
* @param socketTimeout the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder socketTimeout(String socketTimeout) {
doSetProperty("socketTimeout", socketTimeout);
return this;
}
/**
* Enable scroll usage.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useScroll the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder useScroll(boolean useScroll) {
doSetProperty("useScroll", useScroll);
return this;
}
/**
* Enable scroll usage.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useScroll the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder useScroll(String useScroll) {
doSetProperty("useScroll", useScroll);
return this;
}
/**
* Index creation waits for the write consistency number of shards to be
* available.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: producer
*
* @param waitForActiveShards the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder waitForActiveShards(int waitForActiveShards) {
doSetProperty("waitForActiveShards", waitForActiveShards);
return this;
}
/**
* Index creation waits for the write consistency number of shards to be
* available.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1
* Group: producer
*
* @param waitForActiveShards the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder waitForActiveShards(String waitForActiveShards) {
doSetProperty("waitForActiveShards", waitForActiveShards);
return this;
}
/**
* The certificate that can be used to access the ES Cluster. It can be
* loaded by default from classpath, but you can prefix with classpath:,
* file:, or http: to load the resource from different systems.
*
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param certificatePath the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder certificatePath(String certificatePath) {
doSetProperty("certificatePath", certificatePath);
return this;
}
/**
* Enable SSL.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param enableSSL the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder enableSSL(boolean enableSSL) {
doSetProperty("enableSSL", enableSSL);
return this;
}
/**
* Enable SSL.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param enableSSL the value to set
* @return the dsl builder
*/
default OpensearchEndpointBuilder enableSSL(String enableSSL) {
doSetProperty("enableSSL", enableSSL);
return this;
}
}
/**
* Advanced builder for endpoint for the OpenSearch component.
*/
public
|
OpensearchEndpointBuilder
|
java
|
apache__maven
|
compat/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java
|
{
"start": 8809,
"end": 11487
}
|
class ____ {}", realm.getId());
for (Artifact artifact : artifacts) {
String id = artifact.getGroupId() + ":" + artifact.getArtifactId();
if (providedArtifacts.contains(id)) {
log.debug(" Excluded {}", id);
} else {
File file = artifact.getFile();
log.debug(" Included {} located at {}", id, file);
realm.addURL(file.toURI().toURL());
}
}
return CoreExtensionEntry.discoverFrom(
realm,
Collections.singleton(artifacts.get(0).getFile()),
extension.getGroupId() + ":" + extension.getArtifactId(),
extension.getConfiguration());
}
private List<Artifact> resolveExtension(
CoreExtension extension,
RepositorySystemSession repoSession,
List<RemoteRepository> repositories,
DependencyFilter dependencyFilter,
UnaryOperator<String> interpolator)
throws ExtensionResolutionException {
try {
/* TODO: Enhance the PluginDependenciesResolver to provide a
* resolveCoreExtension method which uses a CoreExtension
* object instead of a Plugin as this makes no sense.
*/
Plugin plugin = Plugin.newBuilder()
.groupId(interpolator.apply(extension.getGroupId()))
.artifactId(interpolator.apply(extension.getArtifactId()))
.version(interpolator.apply(extension.getVersion()))
.build();
DependencyResult result = pluginDependenciesResolver.resolveCoreExtension(
new org.apache.maven.model.Plugin(plugin), dependencyFilter, repositories, repoSession);
return result.getArtifactResults().stream()
.filter(ArtifactResult::isResolved)
.map(ArtifactResult::getArtifact)
.collect(Collectors.toList());
} catch (PluginResolutionException | InterpolatorException e) {
throw new ExtensionResolutionException(extension, e);
}
}
private static UnaryOperator<String> createInterpolator(MavenExecutionRequest request) {
Interpolator interpolator = new DefaultInterpolator();
UnaryOperator<String> callback = v -> {
String r = request.getUserProperties().getProperty(v);
if (r == null) {
r = request.getSystemProperties().getProperty(v);
}
return r != null ? r : v;
};
return v -> interpolator.interpolate(v, callback);
}
static
|
realm
|
java
|
resilience4j__resilience4j
|
resilience4j-circuitbreaker/src/test/java/io/github/resilience4j/circuitbreaker/CircuitBreakerEventPublisherTest.java
|
{
"start": 1071,
"end": 5598
}
|
class ____ {
private Logger logger;
private CircuitBreaker circuitBreaker;
@Before
public void setUp() {
logger = mock(Logger.class);
circuitBreaker = CircuitBreaker.ofDefaults("testName");
}
@Test
public void shouldReturnTheSameConsumer() {
CircuitBreaker.EventPublisher eventPublisher = circuitBreaker.getEventPublisher();
CircuitBreaker.EventPublisher eventPublisher2 = circuitBreaker.getEventPublisher();
assertThat(eventPublisher).isEqualTo(eventPublisher2);
}
@Test
public void shouldConsumeOnEvent() {
circuitBreaker.getEventPublisher()
.onEvent(this::logEventType);
circuitBreaker.onSuccess(1000, TimeUnit.NANOSECONDS);
then(logger).should(times(1)).info("SUCCESS");
}
@Test
public void shouldConsumeOnSuccessEvent() {
circuitBreaker.getEventPublisher()
.onSuccess(this::logEventType);
circuitBreaker.onSuccess(1000, TimeUnit.NANOSECONDS);
then(logger).should(times(1)).info("SUCCESS");
}
@Test
public void shouldConsumeOnErrorEvent() {
circuitBreaker.getEventPublisher()
.onError(this::logEventType);
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
then(logger).should(times(1)).info("ERROR");
}
@Test
public void shouldConsumeOnResetEvent() {
circuitBreaker.getEventPublisher()
.onReset(this::logEventType);
circuitBreaker.reset();
then(logger).should(times(1)).info("RESET");
}
@Test
public void shouldConsumeOnStateTransitionEvent() {
circuitBreaker = CircuitBreaker.of("test", CircuitBreakerConfig.custom()
.slidingWindowSize(1).build());
circuitBreaker.getEventPublisher()
.onStateTransition(this::logEventType);
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
then(logger).should(times(1)).info("STATE_TRANSITION");
}
@Test
public void shouldConsumeCallNotPermittedEvent() {
circuitBreaker = CircuitBreaker.of("test", CircuitBreakerConfig.custom()
.slidingWindowSize(1).build());
circuitBreaker.getEventPublisher()
.onCallNotPermitted(this::logEventType);
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
circuitBreaker.tryAcquirePermission();
then(logger).should(times(1)).info("NOT_PERMITTED");
}
@Test
public void shouldNotProduceEventsInDisabledState() {
circuitBreaker = CircuitBreaker.of("test", CircuitBreakerConfig.custom()
.slidingWindowSize(1).build());
circuitBreaker.getEventPublisher()
.onEvent(this::logEventType);
//When we transition to disabled
circuitBreaker.transitionToDisabledState();
//And we execute other calls that should generate events
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
circuitBreaker.tryAcquirePermission();
circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
circuitBreaker.onError(1000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
//Then we do not produce events
then(logger).should(times(1)).info("STATE_TRANSITION");
then(logger).should(times(0)).info("NOT_PERMITTED");
then(logger).should(times(0)).info("SUCCESS");
then(logger).should(times(0)).info("ERROR");
then(logger).should(times(0)).info("IGNORED_ERROR");
}
private void logEventType(CircuitBreakerEvent event) {
logger.info(event.getEventType().toString());
}
@Test
public void shouldConsumeIgnoredErrorEvent() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.ignoreExceptions(IOException.class)
.build();
circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig);
circuitBreaker.getEventPublisher()
.onIgnoredError(this::logEventType);
circuitBreaker.onError(10000, TimeUnit.NANOSECONDS, new IOException("BAM!"));
then(logger).should(times(1)).info("IGNORED_ERROR");
}
}
|
CircuitBreakerEventPublisherTest
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/classes/ClassAssert_hasMethods_Test.java
|
{
"start": 867,
"end": 1194
}
|
class ____ extends ClassAssertBaseTest {
@Override
protected ClassAssert invoke_api_method() {
return assertions.hasMethods("method");
}
@Override
protected void verify_internal_effects() {
verify(classes).assertHasMethods(getInfo(assertions), getActual(assertions), "method");
}
}
|
ClassAssert_hasMethods_Test
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java
|
{
"start": 9698,
"end": 9880
}
|
interface ____ {
ConjunctFuture<?> createFuture(
Collection<? extends java.util.concurrent.CompletableFuture<?>> futures);
}
private static
|
FutureFactory
|
java
|
apache__camel
|
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/TestInstanceDefaultTest.java
|
{
"start": 2334,
"end": 2996
}
|
class ____ {
@Order(1)
@Test
void shouldSupportNestedTestLaunchedFirst() throws Exception {
mock.expectedBodiesReceived(1);
int result = template.requestBody((Object) null, Integer.class);
mock.assertIsSatisfied();
assertEquals(1, result);
}
@Order(2)
@Test
void shouldSupportNestedTestLaunchedSecondWithSameResult() throws Exception {
mock.expectedBodiesReceived(1);
int result = template.requestBody((Object) null, Integer.class);
mock.assertIsSatisfied();
assertEquals(1, result);
}
}
}
|
NestedTest
|
java
|
square__javapoet
|
src/test/java/com/squareup/javapoet/AbstractTypesTest.java
|
{
"start": 5940,
"end": 11681
}
|
class ____<T extends Map<List<T>, Set<T[]>>> {}
@Test
public void getTypeVariableTypeMirrorRecursive() {
TypeMirror typeMirror = getElement(Recursive.class).asType();
ParameterizedTypeName typeName = (ParameterizedTypeName) TypeName.get(typeMirror);
String className = Recursive.class.getCanonicalName();
assertThat(typeName.toString()).isEqualTo(className + "<T>");
TypeVariableName typeVariableName = (TypeVariableName) typeName.typeArguments.get(0);
try {
typeVariableName.bounds.set(0, null);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
assertThat(typeVariableName.toString()).isEqualTo("T");
assertThat(typeVariableName.bounds.toString())
.isEqualTo("[java.util.Map<java.util.List<T>, java.util.Set<T[]>>]");
}
@Test public void getPrimitiveTypeMirror() {
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.BOOLEAN)))
.isEqualTo(TypeName.BOOLEAN);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.BYTE)))
.isEqualTo(TypeName.BYTE);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.SHORT)))
.isEqualTo(TypeName.SHORT);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.INT)))
.isEqualTo(TypeName.INT);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.LONG)))
.isEqualTo(TypeName.LONG);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.CHAR)))
.isEqualTo(TypeName.CHAR);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.FLOAT)))
.isEqualTo(TypeName.FLOAT);
assertThat(TypeName.get(getTypes().getPrimitiveType(TypeKind.DOUBLE)))
.isEqualTo(TypeName.DOUBLE);
}
@Test public void getArrayTypeMirror() {
assertThat(TypeName.get(getTypes().getArrayType(getMirror(Object.class))))
.isEqualTo(ArrayTypeName.of(ClassName.OBJECT));
}
@Test public void getVoidTypeMirror() {
assertThat(TypeName.get(getTypes().getNoType(TypeKind.VOID)))
.isEqualTo(TypeName.VOID);
}
@Test public void getNullTypeMirror() {
try {
TypeName.get(getTypes().getNullType());
fail();
} catch (IllegalArgumentException expected) {
}
}
@Test public void parameterizedType() throws Exception {
ParameterizedTypeName type = ParameterizedTypeName.get(Map.class, String.class, Long.class);
assertThat(type.toString()).isEqualTo("java.util.Map<java.lang.String, java.lang.Long>");
}
@Test public void arrayType() throws Exception {
ArrayTypeName type = ArrayTypeName.of(String.class);
assertThat(type.toString()).isEqualTo("java.lang.String[]");
}
@Test public void wildcardExtendsType() throws Exception {
WildcardTypeName type = WildcardTypeName.subtypeOf(CharSequence.class);
assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence");
}
@Test public void wildcardExtendsObject() throws Exception {
WildcardTypeName type = WildcardTypeName.subtypeOf(Object.class);
assertThat(type.toString()).isEqualTo("?");
}
@Test public void wildcardSuperType() throws Exception {
WildcardTypeName type = WildcardTypeName.supertypeOf(String.class);
assertThat(type.toString()).isEqualTo("? super java.lang.String");
}
@Test public void wildcardMirrorNoBounds() throws Exception {
WildcardType wildcard = getTypes().getWildcardType(null, null);
TypeName type = TypeName.get(wildcard);
assertThat(type.toString()).isEqualTo("?");
}
@Test public void wildcardMirrorExtendsType() throws Exception {
Types types = getTypes();
Elements elements = getElements();
TypeMirror charSequence = elements.getTypeElement(CharSequence.class.getName()).asType();
WildcardType wildcard = types.getWildcardType(charSequence, null);
TypeName type = TypeName.get(wildcard);
assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence");
}
@Test public void wildcardMirrorSuperType() throws Exception {
Types types = getTypes();
Elements elements = getElements();
TypeMirror string = elements.getTypeElement(String.class.getName()).asType();
WildcardType wildcard = types.getWildcardType(null, string);
TypeName type = TypeName.get(wildcard);
assertThat(type.toString()).isEqualTo("? super java.lang.String");
}
@Test public void typeVariable() throws Exception {
TypeVariableName type = TypeVariableName.get("T", CharSequence.class);
assertThat(type.toString()).isEqualTo("T"); // (Bounds are only emitted in declaration.)
}
@Test public void box() throws Exception {
assertThat(TypeName.INT.box()).isEqualTo(ClassName.get(Integer.class));
assertThat(TypeName.VOID.box()).isEqualTo(ClassName.get(Void.class));
assertThat(ClassName.get(Integer.class).box()).isEqualTo(ClassName.get(Integer.class));
assertThat(ClassName.get(Void.class).box()).isEqualTo(ClassName.get(Void.class));
assertThat(TypeName.OBJECT.box()).isEqualTo(TypeName.OBJECT);
assertThat(ClassName.get(String.class).box()).isEqualTo(ClassName.get(String.class));
}
@Test public void unbox() throws Exception {
assertThat(TypeName.INT).isEqualTo(TypeName.INT.unbox());
assertThat(TypeName.VOID).isEqualTo(TypeName.VOID.unbox());
assertThat(ClassName.get(Integer.class).unbox()).isEqualTo(TypeName.INT.unbox());
assertThat(ClassName.get(Void.class).unbox()).isEqualTo(TypeName.VOID.unbox());
try {
TypeName.OBJECT.unbox();
fail();
} catch (UnsupportedOperationException expected) {
}
try {
ClassName.get(String.class).unbox();
fail();
} catch (UnsupportedOperationException expected) {
}
}
}
|
Recursive
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/callbacks/PostLoadLazyListenerTest.java
|
{
"start": 2691,
"end": 2823
}
|
class ____ {
static boolean WAS_CALLED = false;
@PostLoad
void onPreUpdate(Object o) {
WAS_CALLED = true;
}
}
}
|
TagListener
|
java
|
google__gson
|
gson/src/main/java/com/google/gson/ReflectionAccessFilter.java
|
{
"start": 2720,
"end": 4496
}
|
class ____ not accessible by default and would have
* to be made accessible. This is unaffected by any {@code java} command line arguments being
* used to make packages accessible, or by module declaration directives which <i>open</i> the
* complete module or certain packages for reflection and will consider such packages
* inaccessible.
*
* <p>Note that this <b>only works for Java 9 and higher</b>, for older Java versions its
* functionality will be limited and it might behave like {@link #ALLOW}. Access checks are only
* performed as defined by the Java Language Specification (<a
* href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.6">JLS 11
* §6.6</a>), restrictions imposed by a {@link SecurityManager} are not considered.
*
* <p>This result type is mainly intended to help enforce the access checks of the Java Platform
* Module System. It allows detecting illegal access, even if the used Java version would only
* log a warning, or is configured to open packages for reflection using command line arguments.
*
* @see AccessibleObject#canAccess(Object)
*/
BLOCK_INACCESSIBLE,
/**
* Blocks all reflection access for the class. Other means for serializing and deserializing the
* class, such as a {@link TypeAdapter}, have to be used.
*/
BLOCK_ALL
}
/**
* Blocks all reflection access to members of standard Java classes which are not accessible by
* default. However, reflection access is still allowed for classes for which all fields are
* accessible and which have an accessible no-args constructor (or for which an {@link
* InstanceCreator} has been registered).
*
* <p>If this filter encounters a
|
is
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/jdk8/MaybeFromOptionalTest.java
|
{
"start": 746,
"end": 1058
}
|
class ____ extends RxJavaTest {
@Test
public void hasValue() {
Maybe.fromOptional(Optional.of(1))
.test()
.assertResult(1);
}
@Test
public void empty() {
Maybe.fromOptional(Optional.empty())
.test()
.assertResult();
}
}
|
MaybeFromOptionalTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/sp/SamlServiceProviderFactory.java
|
{
"start": 761,
"end": 871
}
|
class ____ creating a {@link SamlServiceProvider} from a {@link SamlServiceProviderDocument}.
*/
public final
|
for
|
java
|
quarkusio__quarkus
|
integration-tests/jpa/src/main/java/io/quarkus/it/jpa/entitylistener/MyListenerRequiringCdiImplicitScope.java
|
{
"start": 844,
"end": 1321
}
|
class ____ instantiated without relying on CDI
// (because we want to test non-CDI attribute converters too).
@Inject
MyCdiContext cdiContext;
private final String ref;
private final BeanInstantiator beanInstantiator;
public MyListenerRequiringCdiImplicitScope() {
this.beanInstantiator = BeanInstantiator.fromCaller();
int ordinal;
if (!ClientProxy.class.isAssignableFrom(getClass())) { // Disregard CDI proxies extending this
|
is
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/query/KvStateLocationRegistryTest.java
|
{
"start": 1519,
"end": 9629
}
|
class ____ {
/** Simple test registering/unregistering state and looking it up again. */
@Test
void testRegisterAndLookup() throws Exception {
String[] registrationNames = new String[] {"TAsIrGnc7MULwVupNKZ0", "086133IrGn0Ii2853237"};
ExecutionJobVertex[] vertices =
new ExecutionJobVertex[] {createJobVertex(32), createJobVertex(13)};
// IDs for each key group of each vertex
KvStateID[][] ids = new KvStateID[vertices.length][];
for (int i = 0; i < ids.length; i++) {
ids[i] = new KvStateID[vertices[i].getMaxParallelism()];
for (int j = 0; j < vertices[i].getMaxParallelism(); j++) {
ids[i][j] = new KvStateID();
}
}
InetSocketAddress server = new InetSocketAddress(InetAddress.getLocalHost(), 12032);
// Create registry
Map<JobVertexID, ExecutionJobVertex> vertexMap = createVertexMap(vertices);
KvStateLocationRegistry registry = new KvStateLocationRegistry(new JobID(), vertexMap);
// Register
for (int i = 0; i < vertices.length; i++) {
int numKeyGroups = vertices[i].getMaxParallelism();
for (int keyGroupIndex = 0; keyGroupIndex < numKeyGroups; keyGroupIndex++) {
// Register
registry.notifyKvStateRegistered(
vertices[i].getJobVertexId(),
new KeyGroupRange(keyGroupIndex, keyGroupIndex),
registrationNames[i],
ids[i][keyGroupIndex],
server);
}
}
// Verify all registrations
for (int i = 0; i < vertices.length; i++) {
KvStateLocation location = registry.getKvStateLocation(registrationNames[i]);
assertThat(location).isNotNull();
int maxParallelism = vertices[i].getMaxParallelism();
for (int keyGroupIndex = 0; keyGroupIndex < maxParallelism; keyGroupIndex++) {
assertThat(location.getKvStateID(keyGroupIndex)).isEqualTo(ids[i][keyGroupIndex]);
assertThat(location.getKvStateServerAddress(keyGroupIndex)).isEqualTo(server);
}
}
// Unregister
for (int i = 0; i < vertices.length; i++) {
int numKeyGroups = vertices[i].getMaxParallelism();
JobVertexID jobVertexId = vertices[i].getJobVertexId();
for (int keyGroupIndex = 0; keyGroupIndex < numKeyGroups; keyGroupIndex++) {
registry.notifyKvStateUnregistered(
jobVertexId,
new KeyGroupRange(keyGroupIndex, keyGroupIndex),
registrationNames[i]);
}
}
for (int i = 0; i < registrationNames.length; i++) {
assertThat(registry.getKvStateLocation(registrationNames[i])).isNull();
}
}
/** Tests that registrations with duplicate names throw an Exception. */
@Test
void testRegisterDuplicateName() throws Exception {
ExecutionJobVertex[] vertices =
new ExecutionJobVertex[] {createJobVertex(32), createJobVertex(13)};
Map<JobVertexID, ExecutionJobVertex> vertexMap = createVertexMap(vertices);
String registrationName = "duplicated-name";
KvStateLocationRegistry registry = new KvStateLocationRegistry(new JobID(), vertexMap);
// First operator registers
registry.notifyKvStateRegistered(
vertices[0].getJobVertexId(),
new KeyGroupRange(0, 0),
registrationName,
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 12328));
assertThatThrownBy(
() ->
// Second operator registers same name
registry.notifyKvStateRegistered(
vertices[1].getJobVertexId(),
new KeyGroupRange(0, 0),
registrationName,
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 12032)))
.withFailMessage("Did not throw expected Exception after duplicated name")
.isInstanceOf(IllegalStateException.class);
}
/** Tests exception on unregistration before registration. */
@Test
void testUnregisterBeforeRegister() throws Exception {
ExecutionJobVertex vertex = createJobVertex(4);
Map<JobVertexID, ExecutionJobVertex> vertexMap = createVertexMap(vertex);
KvStateLocationRegistry registry = new KvStateLocationRegistry(new JobID(), vertexMap);
assertThatThrownBy(
() ->
registry.notifyKvStateUnregistered(
vertex.getJobVertexId(),
new KeyGroupRange(0, 0),
"any-name"))
.withFailMessage(
"Did not throw expected Exception, because of missing registration")
.isInstanceOf(IllegalArgumentException.class);
}
/** Tests failures during unregistration. */
@Test
void testUnregisterFailures() throws Exception {
String name = "IrGnc73237TAs";
ExecutionJobVertex[] vertices =
new ExecutionJobVertex[] {createJobVertex(32), createJobVertex(13)};
Map<JobVertexID, ExecutionJobVertex> vertexMap = new HashMap<>();
for (ExecutionJobVertex vertex : vertices) {
vertexMap.put(vertex.getJobVertexId(), vertex);
}
KvStateLocationRegistry registry = new KvStateLocationRegistry(new JobID(), vertexMap);
// First operator registers name
registry.notifyKvStateRegistered(
vertices[0].getJobVertexId(),
new KeyGroupRange(0, 0),
name,
new KvStateID(),
mock(InetSocketAddress.class));
// Unregister not registered keyGroupIndex
int notRegisteredKeyGroupIndex = 2;
assertThatThrownBy(
() ->
registry.notifyKvStateUnregistered(
vertices[0].getJobVertexId(),
new KeyGroupRange(
notRegisteredKeyGroupIndex,
notRegisteredKeyGroupIndex),
name))
.withFailMessage("Did not throw expected Exception")
.isInstanceOf(IllegalArgumentException.class);
// Wrong operator tries to unregister
assertThatThrownBy(
() ->
registry.notifyKvStateUnregistered(
vertices[1].getJobVertexId(),
new KeyGroupRange(0, 0),
name))
.withFailMessage("Did not throw expected Exception")
.isInstanceOf(IllegalArgumentException.class);
}
// ------------------------------------------------------------------------
private ExecutionJobVertex createJobVertex(int maxParallelism) {
JobVertexID id = new JobVertexID();
ExecutionJobVertex vertex = mock(ExecutionJobVertex.class);
when(vertex.getJobVertexId()).thenReturn(id);
when(vertex.getMaxParallelism()).thenReturn(maxParallelism);
return vertex;
}
private Map<JobVertexID, ExecutionJobVertex> createVertexMap(ExecutionJobVertex... vertices) {
Map<JobVertexID, ExecutionJobVertex> vertexMap = new HashMap<>();
for (ExecutionJobVertex vertex : vertices) {
vertexMap.put(vertex.getJobVertexId(), vertex);
}
return vertexMap;
}
}
|
KvStateLocationRegistryTest
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/SerializationOrderTest.java
|
{
"start": 440,
"end": 757
}
|
class ____
{
public int a;
public int b;
public int c;
@JsonCreator
public BeanWithCreator(@JsonProperty("c") int c, @JsonProperty("a") int a) {
this.a = a;
this.c = c;
}
}
@JsonPropertyOrder({"c", "a", "b"})
static
|
BeanWithCreator
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/views/ViewDeserializationTest.java
|
{
"start": 1085,
"end": 4694
}
|
class ____
{
@JsonView(ViewA.class)
public Integer a;
@JsonView(ViewB.class)
public Integer b;
@JsonCreator
public ViewsAndCreatorBean(@JsonProperty("a") Integer a,
@JsonProperty("b") Integer b)
{
this.a = a;
this.b = b;
}
}
/*
/************************************************************************
/* Tests
/************************************************************************
*/
private final ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_UNEXPECTED_VIEW_PROPERTIES)
.build();
@Test
public void testSimple() throws Exception
{
// by default, should have it all...
Bean bean = mapper
.readValue("{\"a\":3, \"aa\":\"foo\", \"b\": 9 }", Bean.class);
assertEquals(3, bean.a);
assertEquals("foo", bean.aa);
assertEquals(9, bean.b);
// but with different views, different contents
bean = mapper.readerWithView(ViewAA.class)
.forType(Bean.class)
.readValue("{\"a\":3, \"aa\":\"foo\", \"b\": 9 }");
// should include 'a' and 'aa' (as per view)
assertEquals(3, bean.a);
assertEquals("foo", bean.aa);
// but not 'b'
assertEquals(0, bean.b);
bean = mapper.readerWithView(ViewA.class)
.forType(Bean.class)
.readValue("{\"a\":1, \"aa\":\"x\", \"b\": 3 }");
assertEquals(1, bean.a);
assertNull(bean.aa);
assertEquals(0, bean.b);
bean = mapper.readerFor(Bean.class)
.withView(ViewB.class)
.readValue("{\"a\":-3, \"aa\":\"y\", \"b\": 2 }");
assertEquals(0, bean.a);
assertEquals("y", bean.aa);
assertEquals(2, bean.b);
}
@Test
public void testWithoutDefaultInclusion() throws Exception
{
// without active view, all included still:
DefaultsBean bean = mapper
.readValue("{\"a\":3, \"b\": 9 }", DefaultsBean.class);
assertEquals(3, bean.a);
assertEquals(9, bean.b);
ObjectMapper myMapper = jsonMapperBuilder()
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.disable(DeserializationFeature.FAIL_ON_UNEXPECTED_VIEW_PROPERTIES)
.build();
// but with, say, AA, will not get 'b'
bean = myMapper.readerWithView(ViewAA.class)
.forType(DefaultsBean.class)
.readValue("{\"a\":1, \"b\": 2 }");
// 'a' not there any more
assertEquals(0, bean.a);
assertEquals(2, bean.b);
}
@Test
public void testWithCreatorAndViews() throws Exception
{
ViewsAndCreatorBean result;
result = mapper.readerFor(ViewsAndCreatorBean.class)
.withView(ViewA.class)
.readValue(a2q("{'a':1,'b':2}"));
assertEquals(1, result.a);
assertEquals(null, result.b);
result = mapper.readerFor(ViewsAndCreatorBean.class)
.withView(ViewB.class)
.readValue(a2q("{'a':1,'b':2}"));
assertEquals(null, result.a);
assertEquals(2, result.b);
// and actually... fine to skip incompatible stuff too
result = mapper.readerFor(ViewsAndCreatorBean.class)
.withView(ViewB.class)
.readValue(a2q("{'a':[ 1, 23, { } ],'b':2}"));
assertEquals(null, result.a);
assertEquals(2, result.b);
}
}
|
ViewsAndCreatorBean
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/collect/testing/google/SetMultimapTestSuiteBuilder.java
|
{
"start": 4793,
"end": 5246
}
|
class ____<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<V> create(Object... elements) {
return (Set<V>) super.create(elements);
}
}
static final
|
MultimapGetGenerator
|
java
|
elastic__elasticsearch
|
x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/action/cache/FrozenCacheInfoResponse.java
|
{
"start": 517,
"end": 1041
}
|
class ____ extends ActionResponse {
private final boolean hasFrozenCache;
FrozenCacheInfoResponse(boolean hasFrozenCache) {
this.hasFrozenCache = hasFrozenCache;
}
FrozenCacheInfoResponse(StreamInput in) throws IOException {
hasFrozenCache = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeBoolean(hasFrozenCache);
}
public boolean hasFrozenCache() {
return hasFrozenCache;
}
}
|
FrozenCacheInfoResponse
|
java
|
spring-projects__spring-boot
|
module/spring-boot-integration/src/main/java/org/springframework/boot/integration/autoconfigure/IntegrationProperties.java
|
{
"start": 1114,
"end": 1808
}
|
class ____ {
private final Channel channel = new Channel();
private final Endpoint endpoint = new Endpoint();
private final Error error = new Error();
private final RSocket rsocket = new RSocket();
private final Poller poller = new Poller();
private final Management management = new Management();
public Channel getChannel() {
return this.channel;
}
public Endpoint getEndpoint() {
return this.endpoint;
}
public Error getError() {
return this.error;
}
public RSocket getRsocket() {
return this.rsocket;
}
public Poller getPoller() {
return this.poller;
}
public Management getManagement() {
return this.management;
}
public static
|
IntegrationProperties
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-testing/src/main/java/io/quarkus/devtools/testing/registry/client/TestRegistryClientBuilder.java
|
{
"start": 42712,
"end": 45371
}
|
class ____ {
private final TestRegistryBuilder registry;
private final ExtensionCatalog.Mutable extensions = ExtensionCatalog.builder();
private List<TestCodestartBuilder> codestarts = List.of();
private TestNonPlatformCatalogBuilder(TestRegistryBuilder registry, String quarkusVersion) {
this.registry = registry;
final ArtifactCoords baseCoords = registry.getRegistryNonPlatformCatalogArtifact();
extensions.setId(ArtifactCoords.of(baseCoords.getGroupId(), baseCoords.getArtifactId(), quarkusVersion,
baseCoords.getType(), baseCoords.getVersion()).toString());
extensions.setPlatform(false);
extensions.setQuarkusCoreVersion(quarkusVersion);
extensions.setBom(ArtifactCoords.pom("io.quarkus", "quarkus-bom", quarkusVersion));
}
public TestNonPlatformCatalogBuilder addExtension(String groupId, String artifactId, String version) {
addExtensionToCatalog(groupId, artifactId, version);
return this;
}
private Extension.Mutable addExtensionToCatalog(String groupId, String artifactId, String version) {
Extension.Mutable e = Extension.builder()
.setArtifact(ArtifactCoords.jar(groupId, artifactId, version))
.setName(artifactId)
.setOrigins(Collections.singletonList(extensions));
extensions.addExtension(e);
return e;
}
public TestNonPlatformCodestartBuilder addExtensionWithCodestart(String groupId, String artifactId, String version) {
var codestartBuilder = new TestNonPlatformCodestartBuilder(addExtensionToCatalog(groupId, artifactId, version),
this);
if (codestarts.isEmpty()) {
codestarts = new ArrayList<>();
}
codestarts.add(codestartBuilder);
return codestartBuilder;
}
public TestRegistryBuilder registry() {
return registry;
}
private void persist(Path nonPlatformDir) {
codestarts.forEach(TestCodestartBuilder::persist);
final Path json = getNonPlatformCatalogPath(nonPlatformDir, extensions.getQuarkusCoreVersion());
try {
extensions.persist(json);
} catch (IOException e) {
throw new IllegalStateException("Failed to persist extension catalog " + json, e);
}
registry().clientBuilder().installExtensionArtifacts(extensions.getExtensions());
}
}
public static
|
TestNonPlatformCatalogBuilder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java
|
{
"start": 14860,
"end": 15510
}
|
class ____ extends SqlExpressionTranslator<IsNull> {
@Override
protected QueryTranslation asQuery(IsNull isNull, boolean onAggs, TranslatorHandler handler) {
Query query = null;
AggFilter aggFilter = null;
if (onAggs) {
aggFilter = new AggFilter(id(isNull), isNull.asScript());
} else {
query = ExpressionTranslators.IsNulls.doTranslate(isNull, handler);
}
return new QueryTranslation(query, aggFilter);
}
}
// assume the Optimizer properly orders the predicates to ease the translation
static
|
IsNullTranslator
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/jdk8/FlowableFromCompletionStage.java
|
{
"start": 1067,
"end": 1801
}
|
class ____<T> extends Flowable<T> {
final CompletionStage<T> stage;
public FlowableFromCompletionStage(CompletionStage<T> stage) {
this.stage = stage;
}
@Override
protected void subscribeActual(Subscriber<? super T> s) {
// We need an indirection because one can't detach from a whenComplete
// and cancellation should not hold onto the stage.
BiConsumerAtomicReference<T> whenReference = new BiConsumerAtomicReference<>();
CompletionStageHandler<T> handler = new CompletionStageHandler<>(s, whenReference);
whenReference.lazySet(handler);
s.onSubscribe(handler);
stage.whenComplete(whenReference);
}
static final
|
FlowableFromCompletionStage
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAbfsOutputStreamStatistics.java
|
{
"start": 10142,
"end": 10386
}
|
class ____ get the
* values of the counters.
*/
private static AbfsOutputStreamStatisticsImpl getAbfsOutputStreamStatistics(
AbfsOutputStream out) {
return (AbfsOutputStreamStatisticsImpl) out.getOutputStreamStatistics();
}
}
|
to
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/CompilationWarningsTest.java
|
{
"start": 328,
"end": 9497
}
|
class ____ {
@Before
public void pay_attention_to_compilation_warnings_and_JDK_version() {}
@Test
public void no_warnings_for_most_common_api() throws Exception {
doReturn(null).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doReturn("a", 12).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doReturn(1000).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doThrow(new NullPointerException())
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doThrow(new NullPointerException(), new IllegalArgumentException())
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doThrow(NullPointerException.class)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doAnswer(ignore()).doReturn(null).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doAnswer(ignore())
.doReturn("a", 12)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doAnswer(ignore()).doReturn(1000).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doAnswer(ignore())
.doThrow(new NullPointerException())
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doAnswer(ignore())
.doThrow(new NullPointerException(), new IllegalArgumentException())
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
doAnswer(ignore())
.doThrow(NullPointerException.class)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(null);
when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn("a", 12L);
when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(1000);
when(mock(IMethods.class).objectReturningMethodNoArgs())
.thenThrow(new NullPointerException());
when(mock(IMethods.class).objectReturningMethodNoArgs())
.thenThrow(new NullPointerException(), new IllegalArgumentException());
when(mock(IMethods.class).objectReturningMethodNoArgs())
.thenThrow(NullPointerException.class);
when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn(null);
when(mock(IMethods.class).objectReturningMethodNoArgs())
.then(ignore())
.thenReturn("a", 12L);
when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn(1000);
when(mock(IMethods.class).objectReturningMethodNoArgs())
.then(ignore())
.thenThrow(new NullPointerException());
when(mock(IMethods.class).objectReturningMethodNoArgs())
.then(ignore())
.thenThrow(new NullPointerException(), new IllegalArgumentException());
when(mock(IMethods.class).objectReturningMethodNoArgs())
.then(ignore())
.thenThrow(NullPointerException.class);
willReturn(null).given(mock(IMethods.class)).objectReturningMethodNoArgs();
willReturn("a", 12).given(mock(IMethods.class)).objectReturningMethodNoArgs();
willReturn(1000).given(mock(IMethods.class)).objectReturningMethodNoArgs();
willThrow(new NullPointerException())
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willThrow(new NullPointerException(), new IllegalArgumentException())
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willThrow(NullPointerException.class)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willReturn(null)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willReturn("a", 12)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willReturn(1000)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willThrow(new NullPointerException())
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willThrow(new NullPointerException(), new IllegalArgumentException())
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
willAnswer(ignore())
.willThrow(NullPointerException.class)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(null);
given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn("a", 12L);
given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(1000);
given(mock(IMethods.class).objectReturningMethodNoArgs())
.willThrow(new NullPointerException());
given(mock(IMethods.class).objectReturningMethodNoArgs())
.willThrow(new NullPointerException(), new IllegalArgumentException());
given(mock(IMethods.class).objectReturningMethodNoArgs())
.willThrow(NullPointerException.class);
given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn(null);
given(mock(IMethods.class).objectReturningMethodNoArgs())
.will(ignore())
.willReturn("a", 12L);
given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn(1000);
given(mock(IMethods.class).objectReturningMethodNoArgs())
.will(ignore())
.willThrow(new NullPointerException());
given(mock(IMethods.class).objectReturningMethodNoArgs())
.will(ignore())
.willThrow(new NullPointerException(), new IllegalArgumentException());
given(mock(IMethods.class).objectReturningMethodNoArgs())
.will(ignore())
.willThrow(NullPointerException.class);
}
@Test
@SuppressWarnings("unchecked")
public void
heap_pollution_JDK7plus_warning_avoided_BUT_now_unchecked_generic_array_creation_warnings_ON_JDK5plus_environment()
throws Exception {
doThrow(NullPointerException.class, IllegalArgumentException.class)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
when(mock(IMethods.class).objectReturningMethodNoArgs())
.thenThrow(NullPointerException.class, IllegalArgumentException.class);
doAnswer(ignore())
.doThrow(NullPointerException.class, IllegalArgumentException.class)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
willThrow(NullPointerException.class, IllegalArgumentException.class)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
given(mock(IMethods.class).objectReturningMethodNoArgs())
.willThrow(NullPointerException.class, IllegalArgumentException.class);
willAnswer(ignore())
.willThrow(NullPointerException.class, IllegalArgumentException.class)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
}
@Test
public void unchecked_confusing_null_argument_warnings() throws Exception {
doReturn(null, (Object[]) null).when(mock(IMethods.class)).objectReturningMethodNoArgs();
doAnswer(ignore())
.doReturn(null, (Object[]) null)
.when(mock(IMethods.class))
.objectReturningMethodNoArgs();
when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(null, (Object[]) null);
when(mock(IMethods.class).objectReturningMethodNoArgs())
.then(ignore())
.thenReturn(null, (Object[]) null);
willReturn(null, (Object[]) null).given(mock(IMethods.class)).objectReturningMethodNoArgs();
given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(null, (Object[]) null);
willAnswer(ignore())
.willReturn(null, (Object[]) null)
.given(mock(IMethods.class))
.objectReturningMethodNoArgs();
given(mock(IMethods.class).objectReturningMethodNoArgs())
.will(ignore())
.willReturn(null, (Object[]) null);
}
private static Answer<?> ignore() {
return new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null;
}
};
}
}
|
CompilationWarningsTest
|
java
|
google__error-prone
|
test_helpers/src/test/java/com/google/errorprone/CompilationTestHelperTest.java
|
{
"start": 4396,
"end": 5023
}
|
class ____ {
public boolean doIt() {
// BUG: Diagnostic matches: X
return true;
}
}
""")
.expectErrorMessage("X", Predicates.containsPattern("Method may return normally"))
.doTest();
}
@Test
public void fileWithBugMarkerAndErrorOnWrongLineFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"""
public
|
Test
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest_NoneASM.java
|
{
"start": 3731,
"end": 4115
}
|
class ____ {
private double f0;
private double f1;
public double getF0() {
return f0;
}
public void setF0(double f0) {
this.f0 = f0;
}
public double getF1() {
return f1;
}
public void setF1(double f1) {
this.f1 = f1;
}
}
private static
|
VO_Double
|
java
|
junit-team__junit5
|
junit-jupiter-api/src/main/java/org/junit/jupiter/api/DisplayNameGenerator.java
|
{
"start": 12741,
"end": 12827
}
|
interface ____ {
/**
* Custom sentence fragment for the annotated
|
SentenceFragment
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/collect/testing/testers/MapReplaceTester.java
|
{
"start": 2029,
"end": 4133
}
|
class ____<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testReplace_supportedPresent() {
try {
assertEquals(v0(), getMap().replace(k0(), v3()));
expectReplacement(entry(k0(), v3()));
} catch (ClassCastException tolerated) { // for ClassToInstanceMap
expectUnchanged();
}
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testReplace_supportedPresentNoChange() {
assertEquals(v0(), getMap().replace(k0(), v0()));
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testReplace_supportedAbsent() {
assertNull(getMap().replace(k3(), v3()));
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testReplace_presentNullValueUnsupported() {
assertThrows(NullPointerException.class, () -> getMap().replace(k0(), null));
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUE_QUERIES)
public void testReplace_absentNullValueUnsupported() {
try {
getMap().replace(k3(), null);
} catch (NullPointerException tolerated) {
// permitted not to throw because it would be a no-op
}
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEY_QUERIES)
public void testReplace_absentNullKeyUnsupported() {
try {
getMap().replace(null, v3());
} catch (NullPointerException tolerated) {
// permitted not to throw because it would be a no-op
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testReplace_unsupportedPresent() {
try {
getMap().replace(k0(), v3());
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
} catch (ClassCastException tolerated) {
// for ClassToInstanceMap
}
expectUnchanged();
}
}
|
MapReplaceTester
|
java
|
google__guice
|
core/src/com/google/inject/spi/ErrorDetail.java
|
{
"start": 509,
"end": 4468
}
|
class ____<SelfT extends ErrorDetail<SelfT>> implements Serializable {
private final String message;
private final ImmutableList<Object> sources;
private final Throwable cause;
protected ErrorDetail(String message, List<Object> sources, Throwable cause) {
this.message = message;
this.sources = ImmutableList.copyOf(sources);
this.cause = cause;
}
/**
* Returns true if this error can be merged with the {@code otherError} and formatted together.
*
* <p>By default this return false and implementations that support merging with other errors
* should override this method.
*/
public boolean isMergeable(ErrorDetail<?> otherError) {
return false;
}
/**
* Formats this error along with other errors that are mergeable with this error.
*
* <p>{@code mergeableErrors} is a list that contains all other errors that are reported in the
* same exception that are considered to be mergable with this error base on result of calling
* {@link #isMergeable}. The list will be empty if non of the other errors are mergable with this
* error.
*
* <p>Formatted error has the following structure:
*
* <ul>
* <li>Summary of the error
* <li>Details about the error such as the source of the error
* <li>Hints for fixing the error if available
* <li>Link to the documentation on this error in greater detail
* </ul>
*
* @param index index for this error
* @param mergeableErrors list of errors that are mergeable with this error
* @param formatter for printing the error message
*/
public final void format(int index, List<ErrorDetail<?>> mergeableErrors, Formatter formatter) {
String id = getErrorIdentifier().map(s -> "[" + Messages.redBold(s) + "]: ").orElse("");
formatter.format("%s) %s%s\n", index, id, getMessage());
formatDetail(mergeableErrors, formatter);
// TODO(b/151482394): Output potiential fixes for the error
Optional<String> learnMoreLink = getLearnMoreLink();
if (learnMoreLink.isPresent()) {
formatter.format("\n%s\n", Messages.bold("Learn more:"));
formatter.format(" %s\n", Messages.underline(learnMoreLink.get()));
}
}
/**
* Formats the detail of this error message along with other errors that are mergeable with this
* error. This is called from {@link #format}.
*
* <p>{@code mergeableErrors} is a list that contains all other errors that are reported in the
* same exception that are considered to be mergable with this error base on result of calling
* {@link #isMergeable}. The list will be empty if non of the other errors are mergable with this
* error.
*
* @param mergeableErrors list of errors that are mergeable with this error
* @param formatter for printing the error message
*/
protected abstract void formatDetail(List<ErrorDetail<?>> mergeableErrors, Formatter formatter);
/**
* Returns an optional link to additional documentation about this error to be included in the
* formatted error message.
*/
protected Optional<String> getLearnMoreLink() {
return Optional.empty();
}
/** Returns an optional string identifier for this error. */
protected Optional<String> getErrorIdentifier() {
return Optional.empty();
}
public String getMessage() {
return message;
}
public List<Object> getSources() {
return sources;
}
public Throwable getCause() {
return cause;
}
@Override
public int hashCode() {
return Objects.hashCode(message, cause, sources);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ErrorDetail)) {
return false;
}
ErrorDetail<?> e = (ErrorDetail<?>) o;
return message.equals(e.message) && Objects.equal(cause, e.cause) && sources.equals(e.sources);
}
/** Returns a new instance of the same {@link ErrorDetail} with updated sources. */
public abstract SelfT withSources(List<Object> newSources);
}
|
ErrorDetail
|
java
|
apache__camel
|
core/camel-base/src/main/java/org/apache/camel/component/properties/RefPropertiesSource.java
|
{
"start": 1077,
"end": 3121
}
|
class ____ implements LocationPropertiesSource, Ordered {
private final int order;
private final PropertiesComponent propertiesComponent;
private final PropertiesLocation location;
public RefPropertiesSource(PropertiesComponent propertiesComponent, PropertiesLocation location) {
this(propertiesComponent, location, 200);
}
public RefPropertiesSource(PropertiesComponent propertiesComponent, PropertiesLocation location, int order) {
this.propertiesComponent = propertiesComponent;
this.location = location;
this.order = order;
}
@Override
public String getName() {
return "RefPropertiesSource[" + getLocation().getPath() + "]";
}
@Override
public PropertiesLocation getLocation() {
return location;
}
@Override
public String getProperty(String name) {
// this will lookup the property on-demand
Properties properties = lookupPropertiesInRegistry(propertiesComponent, location);
if (properties != null) {
return properties.getProperty(name);
} else {
return null;
}
}
protected Properties lookupPropertiesInRegistry(PropertiesComponent propertiesComponent, PropertiesLocation location) {
String path = location.getPath();
Properties answer = null;
Object obj = propertiesComponent.getCamelContext().getRegistry().lookupByName(path);
if (obj instanceof Properties) {
answer = (Properties) obj;
} else if (obj instanceof Map) {
answer = new OrderedProperties();
answer.putAll((Map<?, ?>) obj);
} else if (!propertiesComponent.isIgnoreMissingLocation() && !location.isOptional()) {
throw RuntimeCamelException
.wrapRuntimeCamelException(new FileNotFoundException("Properties " + path + " not found in registry"));
}
return answer;
}
@Override
public int getOrder() {
return order;
}
}
|
RefPropertiesSource
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/indices/SystemIndexMappingUpdateServiceTests.java
|
{
"start": 3202,
"end": 20490
}
|
class ____ extends ESTestCase {
private static final ClusterName CLUSTER_NAME = new ClusterName("security-index-manager-tests");
private static final ClusterState EMPTY_CLUSTER_STATE = new ClusterState.Builder(CLUSTER_NAME).build();
private static final String SYSTEM_INDEX_NAME = ".myindex-1";
private static final SystemIndexDescriptor DESCRIPTOR = SystemIndexDescriptor.builder()
.setIndexPattern(".myindex-*")
.setPrimaryIndex(SYSTEM_INDEX_NAME)
.setAliasName(".myindex")
.setIndexFormat(6)
.setSettings(getSettings())
.setMappings(getMappings())
.setOrigin("FAKE_ORIGIN")
.build();
private static final SystemIndices.Feature FEATURE = new SystemIndices.Feature("foo", "a test feature", List.of(DESCRIPTOR));
private Client client;
@Before
public void setUpManager() {
client = mock(Client.class);
final ThreadPool threadPool = mock(ThreadPool.class);
when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
when(threadPool.generic()).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE);
when(client.threadPool()).thenReturn(threadPool);
when(client.settings()).thenReturn(Settings.EMPTY);
}
/**
* Check that the manager skips over descriptors whose indices cannot be managed.
*/
public void testManagerSkipsDescriptorsThatAreNotManaged() {
SystemIndexDescriptor d1 = SystemIndexDescriptorUtils.createUnmanaged(".foo-1*", "");
SystemIndexDescriptor d2 = SystemIndexDescriptor.builder()
.setIndexPattern(".bar-*")
.setPrimaryIndex(".bar-1")
.setMappings(getMappings())
.setSettings(getSettings())
.setIndexFormat(6)
.setOrigin("FAKE_ORIGIN")
.build();
SystemIndices systemIndices = new SystemIndices(
List.of(
new SystemIndices.Feature("index 1", "index 1 feature", List.of(d1)),
new SystemIndices.Feature("index 2", "index 2 feature", List.of(d2))
)
);
final var projectId = randomProjectIdOrDefault();
SystemIndexMappingUpdateService manager = new SystemIndexMappingUpdateService(
systemIndices,
client,
TestProjectResolvers.singleProject(projectId)
);
final List<SystemIndexDescriptor> eligibleDescriptors = manager.getEligibleDescriptors(
ProjectMetadata.builder(projectId)
.put(getIndexMetadata(d1, null, 6, IndexMetadata.State.OPEN))
.put(getIndexMetadata(d2, d2.getMappings(), 6, IndexMetadata.State.OPEN))
.build()
);
assertThat(eligibleDescriptors, hasSize(1));
assertThat(eligibleDescriptors, contains(d2));
}
/**
* Check that the manager skips over indices that don't exist yet, since system indices are
* created on-demand.
*/
public void testManagerSkipsDescriptorsForIndicesThatDoNotExist() {
SystemIndexDescriptor d1 = SystemIndexDescriptor.builder()
.setIndexPattern(".foo-*")
.setPrimaryIndex(".foo-1")
.setMappings(getMappings())
.setSettings(getSettings())
.setIndexFormat(6)
.setOrigin("FAKE_ORIGIN")
.build();
SystemIndexDescriptor d2 = SystemIndexDescriptor.builder()
.setIndexPattern(".bar-*")
.setPrimaryIndex(".bar-1")
.setMappings(getMappings())
.setSettings(getSettings())
.setIndexFormat(6)
.setOrigin("FAKE_ORIGIN")
.build();
SystemIndices systemIndices = new SystemIndices(
List.of(
new SystemIndices.Feature("index 1", "index 1 feature", List.of(d1)),
new SystemIndices.Feature("index 2", "index 2 feature", List.of(d2))
)
);
final var projectId = randomProjectIdOrDefault();
SystemIndexMappingUpdateService manager = new SystemIndexMappingUpdateService(
systemIndices,
client,
TestProjectResolvers.singleProject(projectId)
);
final List<SystemIndexDescriptor> eligibleDescriptors = manager.getEligibleDescriptors(
ProjectMetadata.builder(projectId).put(getIndexMetadata(d2, d2.getMappings(), 6, IndexMetadata.State.OPEN)).build()
);
assertThat(eligibleDescriptors, hasSize(1));
assertThat(eligibleDescriptors, contains(d2));
}
/**
* Check that the manager won't try to upgrade closed indices.
*/
public void testManagerSkipsClosedIndices() {
final ProjectState projectState = createProjectState(IndexMetadata.State.CLOSE);
assertThat(SystemIndexMappingUpdateService.getUpgradeStatus(projectState, DESCRIPTOR), equalTo(UpgradeStatus.CLOSED));
}
/**
* Check that the manager won't try to upgrade unhealthy indices.
*/
public void testManagerSkipsIndicesWithRedStatus() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(markShardsUnavailable(createProjectState()), DESCRIPTOR),
equalTo(UpgradeStatus.UNHEALTHY)
);
}
/**
* Check that the manager won't try to upgrade indices where the `index.format` setting
* is earlier than an expected value.
*/
public void testManagerSkipsIndicesWithOutdatedFormat() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(markShardsAvailable(createProjectState(5)), DESCRIPTOR),
equalTo(UpgradeStatus.NEEDS_UPGRADE)
);
}
/**
* Check that the manager won't try to upgrade indices where their mappings are already up-to-date.
*/
public void testManagerSkipsIndicesWithUpToDateMappings() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(markShardsAvailable(createProjectState()), DESCRIPTOR),
equalTo(UpgradeStatus.UP_TO_DATE)
);
}
/**
* Check that the manager will try to upgrade indices when we have the old mappings version but not the new one
*/
public void testManagerProcessesIndicesWithOldMappingsVersion() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(
markShardsAvailable(createProjectState(Strings.toString(getMappings("1.0.0", null)))),
DESCRIPTOR
),
equalTo(UpgradeStatus.NEEDS_MAPPINGS_UPDATE)
);
}
/**
* Check that the manager will try to upgrade indices where their mappings are out-of-date.
*/
public void testManagerProcessesIndicesWithOutdatedMappings() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(
markShardsAvailable(createProjectState(Strings.toString(getMappings("1.0.0", 4)))),
DESCRIPTOR
),
equalTo(UpgradeStatus.NEEDS_MAPPINGS_UPDATE)
);
}
/**
* Check that the manager will try to upgrade indices where the mappings metadata is null or absent.
*/
public void testManagerProcessesIndicesWithNullMetadata() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(
markShardsAvailable(createProjectState(Strings.toString(getMappings(builder -> {})))),
DESCRIPTOR
),
equalTo(UpgradeStatus.NEEDS_MAPPINGS_UPDATE)
);
}
/**
* Check that the manager will try to upgrade indices where the version in the metadata is null or absent.
*/
public void testManagerProcessesIndicesWithNullVersionMetadata() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(
markShardsAvailable(createProjectState(Strings.toString(getMappings((String) null, null)))),
DESCRIPTOR
),
equalTo(UpgradeStatus.NEEDS_MAPPINGS_UPDATE)
);
}
/**
* Check that the manager submits the expected request for an index whose mappings are out-of-date.
*/
public void testManagerSubmitsPutRequest() {
SystemIndices systemIndices = new SystemIndices(List.of(FEATURE));
final ProjectState projectState = createProjectState(Strings.toString(getMappings("1.0.0", 4)));
SystemIndexMappingUpdateService manager = new SystemIndexMappingUpdateService(
systemIndices,
client,
TestProjectResolvers.singleProject(projectState.projectId())
);
manager.clusterChanged(event(markShardsAvailable(projectState)));
verify(client, times(1)).execute(same(TransportPutMappingAction.TYPE), any(PutMappingRequest.class), any());
}
/**
* Check that this
*/
public void testCanHandleIntegerMetaVersion() {
assertThat(
SystemIndexMappingUpdateService.getUpgradeStatus(
markShardsAvailable(createProjectState(Strings.toString(getMappings(3)))),
DESCRIPTOR
),
equalTo(UpgradeStatus.NEEDS_MAPPINGS_UPDATE)
);
}
private static ProjectState createProjectState() {
return createProjectState(SystemIndexMappingUpdateServiceTests.DESCRIPTOR.getMappings());
}
private static ProjectState createProjectState(String mappings) {
return createProjectState(mappings, 6, IndexMetadata.State.OPEN);
}
private static ProjectState createProjectState(IndexMetadata.State state) {
return createProjectState(SystemIndexMappingUpdateServiceTests.DESCRIPTOR.getMappings(), 6, state);
}
private static ProjectState createProjectState(int format) {
return createProjectState(SystemIndexMappingUpdateServiceTests.DESCRIPTOR.getMappings(), format, IndexMetadata.State.OPEN);
}
private static ProjectState createProjectState(String mappings, int format, IndexMetadata.State state) {
final var projectId = randomProjectIdOrDefault();
IndexMetadata.Builder indexMeta = getIndexMetadata(SystemIndexMappingUpdateServiceTests.DESCRIPTOR, mappings, format, state);
ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(projectId);
projectBuilder.put(indexMeta);
final DiscoveryNode node = DiscoveryNodeUtils.builder("1").roles(new HashSet<>(DiscoveryNodeRole.roles())).build();
final DiscoveryNodes nodes = DiscoveryNodes.builder().add(node).masterNodeId(node.getId()).localNodeId(node.getId()).build();
final Metadata metadata = Metadata.builder().generateClusterUuidIfNeeded().put(projectBuilder).build();
final ClusterState clusterState = ClusterState.builder(CLUSTER_NAME)
.nodes(nodes)
.metadata(metadata)
.routingTable(GlobalRoutingTableTestHelper.buildRoutingTable(metadata, RoutingTable.Builder::addAsNew))
.build();
return clusterState.projectState(projectId);
}
private ProjectState markShardsAvailable(ProjectState project) {
final ClusterState previousClusterState = project.cluster();
final GlobalRoutingTable routingTable = GlobalRoutingTable.builder(previousClusterState.globalRoutingTable())
.put(project.projectId(), buildIndexRoutingTable(project.metadata().index(DESCRIPTOR.getPrimaryIndex()).getIndex()))
.build();
final ClusterState newClusterState = ClusterState.builder(previousClusterState).routingTable(routingTable).build();
return newClusterState.projectState(project.projectId());
}
private ProjectState markShardsUnavailable(ProjectState projectState) {
Index prevIndex = projectState.routingTable().index(DESCRIPTOR.getPrimaryIndex()).getIndex();
final RoutingTable unavailableRoutingTable = RoutingTable.builder()
.add(
IndexRoutingTable.builder(prevIndex)
.addIndexShard(
IndexShardRoutingTable.builder(new ShardId(prevIndex, 0))
.addShard(
ShardRouting.newUnassigned(
new ShardId(prevIndex, 0),
true,
RecoverySource.ExistingStoreRecoverySource.INSTANCE,
new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, ""),
ShardRouting.Role.DEFAULT
)
.initialize(UUIDs.randomBase64UUID(random()), null, 0L)
.moveToUnassigned(new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, ""))
)
)
)
.build();
return ClusterState.builder(projectState.cluster())
.routingTable(GlobalRoutingTable.builder().put(projectState.projectId(), unavailableRoutingTable).build())
.build()
.projectState(projectState.projectId());
}
private static IndexMetadata.Builder getIndexMetadata(
SystemIndexDescriptor descriptor,
String mappings,
int format,
IndexMetadata.State state
) {
IndexMetadata.Builder indexMetadata = IndexMetadata.builder(
descriptor.isAutomaticallyManaged() ? descriptor.getPrimaryIndex() : descriptor.getIndexPattern()
);
final Settings.Builder settingsBuilder = Settings.builder();
if (descriptor.isAutomaticallyManaged() == false || SystemIndexDescriptor.DEFAULT_SETTINGS.equals(descriptor.getSettings())) {
settingsBuilder.put(getSettings());
} else {
settingsBuilder.put(descriptor.getSettings());
}
settingsBuilder.put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), format);
indexMetadata.settings(settingsBuilder.build());
if (descriptor.isAutomaticallyManaged() && descriptor.getAliasName() != null) {
indexMetadata.putAlias(AliasMetadata.builder(descriptor.getAliasName()).build());
}
indexMetadata.state(state);
if (mappings != null) {
indexMetadata.putMapping(mappings);
}
return indexMetadata;
}
private static RoutingTable buildIndexRoutingTable(Index index) {
ShardRouting shardRouting = ShardRouting.newUnassigned(
new ShardId(index, 0),
true,
RecoverySource.ExistingStoreRecoverySource.INSTANCE,
new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, ""),
ShardRouting.Role.DEFAULT
);
String nodeId = ESTestCase.randomAlphaOfLength(8);
return RoutingTable.builder()
.add(
IndexRoutingTable.builder(index)
.addIndexShard(
IndexShardRoutingTable.builder(new ShardId(index, 0))
.addShard(
shardRouting.initialize(nodeId, null, shardRouting.getExpectedShardSize())
.moveToStarted(ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)
)
)
.build()
)
.build();
}
private ClusterChangedEvent event(ProjectState projectState) {
return new ClusterChangedEvent("test-event", projectState.cluster(), EMPTY_CLUSTER_STATE);
}
private static Settings getSettings() {
return indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6).build();
}
private static XContentBuilder getMappings() {
return getMappings(Version.CURRENT.toString(), 6);
}
private static XContentBuilder getMappings(String nodeVersion, Integer mappingsVersion) {
return getMappings(builder -> builder.object("_meta", meta -> {
meta.field("version", nodeVersion);
meta.field(SystemIndexDescriptor.VERSION_META_KEY, mappingsVersion);
}));
}
// Prior to 7.12.0, .tasks had _meta.version: 3 so we need to be sure we can handle that
private static XContentBuilder getMappings(int version) {
return getMappings(builder -> builder.object("_meta", meta -> meta.field("version", version)));
}
private static XContentBuilder getMappings(CheckedConsumer<XContentBuilder, IOException> metaCallback) {
try {
final XContentBuilder builder = jsonBuilder();
builder.startObject();
{
metaCallback.accept(builder);
builder.field("dynamic", "strict");
builder.startObject("properties");
{
builder.startObject("completed");
builder.field("type", "boolean");
builder.endObject();
}
builder.endObject();
}
builder.endObject();
return builder;
} catch (IOException e) {
throw new UncheckedIOException("Failed to build " + SYSTEM_INDEX_NAME + " index mappings", e);
}
}
}
|
SystemIndexMappingUpdateServiceTests
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/bean/override/BeanOverrideHandlerTests.java
|
{
"start": 11441,
"end": 11589
}
|
class ____ {
@MetaDummyBean()
@DummyBean
String message;
static String foo() {
return "foo";
}
}
static
|
MultipleAnnotationsOnSameField
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/resilience/ReactiveRetryInterceptorTests.java
|
{
"start": 13621,
"end": 13874
}
|
class ____ {
AtomicInteger counter = new AtomicInteger();
public Mono<Object> retryOperation() {
return Mono.fromCallable(() -> {
counter.incrementAndGet();
throw new IOException(counter.toString());
});
}
}
static
|
NonAnnotatedBean
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/EnableAutoConfiguration.java
|
{
"start": 3569,
"end": 3997
}
|
interface ____ {
/**
* Environment property that can be used to override when auto-configuration is
* enabled.
*/
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration
|
EnableAutoConfiguration
|
java
|
quarkusio__quarkus
|
integration-tests/gradle/src/test/java/io/quarkus/gradle/devmode/BasicMultiModuleProjectDevModeTest.java
|
{
"start": 150,
"end": 1042
}
|
class ____ extends QuarkusDevGradleTestBase {
@Override
protected String projectDirectoryName() {
return "basic-multi-module-project";
}
@Override
protected String[] buildArguments() {
return new String[] { "clean", ":application:quarkusDev" };
}
protected void testDevMode() throws Exception {
assertThat(getHttpResponse())
.contains("ready")
.contains("my-quarkus-project")
.contains("org.acme.quarkus.sample")
.contains("1.0-SNAPSHOT");
assertThat(getHttpResponse("/hello")).contains("hello common");
replace("common/src/main/java/org/acme/common/CommonBean.java",
ImmutableMap.of("return \"common\";", "return \"modified\";"));
assertUpdatedResponseContains("/hello", "hello modified");
}
}
|
BasicMultiModuleProjectDevModeTest
|
java
|
apache__camel
|
core/camel-management/src/test/java/org/apache/camel/component/xslt/ManagedXsltOutputBytesTest.java
|
{
"start": 1285,
"end": 2717
}
|
class ____ extends ManagementTestSupport {
@Test
public void testXsltOutput() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("<?xml version=\"1.0\" encoding=\"UTF-8\"?><goodbye>world!</goodbye>");
mock.message(0).body().isInstanceOf(byte[].class);
template.sendBody("direct:start", "<hello>world!</hello>");
assertMockEndpointsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getCamelObjectName(TYPE_ENDPOINT, "xslt://org/apache/camel/component/xslt/example.xsl\\?output=bytes");
String uri = (String) mbeanServer.getAttribute(on, "EndpointUri");
assertEquals("xslt://org/apache/camel/component/xslt/example.xsl?output=bytes", uri);
XsltOutput output = (XsltOutput) mbeanServer.getAttribute(on, "Output");
assertEquals(XsltOutput.bytes, output);
String state = (String) mbeanServer.getAttribute(on, "State");
assertEquals("Started", state);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("xslt:org/apache/camel/component/xslt/example.xsl?output=bytes")
.to("mock:result");
}
};
}
}
|
ManagedXsltOutputBytesTest
|
java
|
apache__camel
|
core/camel-management/src/test/java/org/apache/camel/management/ManagedCanekContextExchangeStatisticsTest.java
|
{
"start": 1274,
"end": 3757
}
|
class ____ extends ManagementTestSupport {
@Test
public void testExchangesCompletedStatistics() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getContextObjectName();
Long completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted");
assertEquals(0, completed.longValue());
ObjectName route1 = getCamelObjectName(TYPE_ROUTE, "route1");
Long completed1 = (Long) mbeanServer.getAttribute(route1, "ExchangesCompleted");
assertEquals(0, completed1.longValue());
ObjectName route2 = getCamelObjectName(TYPE_ROUTE, "route2");
Long completed2 = (Long) mbeanServer.getAttribute(route1, "ExchangesCompleted");
assertEquals(0, completed2.longValue());
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
completed = (Long) mbeanServer.getAttribute(route1, "ExchangesCompleted");
assertEquals(1, completed.longValue());
completed1 = (Long) mbeanServer.getAttribute(route1, "ExchangesCompleted");
assertEquals(1, completed1.longValue());
completed2 = (Long) mbeanServer.getAttribute(route2, "ExchangesCompleted");
assertEquals(0, completed2.longValue());
resetMocks();
getMockEndpoint("mock:result").expectedMessageCount(2);
template.sendBody("direct:start", "Hi World");
template.sendBody("direct:bar", "Bye World");
assertMockEndpointsSatisfied();
completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted");
assertEquals(3, completed.longValue());
completed1 = (Long) mbeanServer.getAttribute(route1, "ExchangesCompleted");
assertEquals(2, completed1.longValue());
completed2 = (Long) mbeanServer.getAttribute(route2, "ExchangesCompleted");
assertEquals(1, completed2.longValue());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.routeId("route1")
.to("log:foo").to("mock:result");
from("direct:bar")
.routeId("route2")
.to("log:bar").to("mock:result");
}
};
}
}
|
ManagedCanekContextExchangeStatisticsTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java
|
{
"start": 3592,
"end": 4749
}
|
class ____ {
private int a1;
private String a2;
private String a3;
private String b1;
private String b2;
private A aObj;
@Id
@Column(name = "A1", nullable = false, length = 15)
public int getA1() {
return a1;
}
public void setA1(int a1) {
this.a1 = a1;
}
@Id
@Column(name = "A2", nullable = false, length = 15)
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
@Id
@Column(name = "A3", nullable = false, length = 15)
public String getA3() {
return a3;
}
public void setA3(String a3) {
this.a3 = a3;
}
@Basic
@Column(name = "B1", nullable = false, length = 15)
public String getB1() {
return b1;
}
public void setB1(String b1) {
this.b1 = b1;
}
@Basic
@Column(name = "B2", nullable = false, length = 15)
public String getB2() {
return b2;
}
public void setB2(String b2) {
this.b2 = b2;
}
@ManyToOne(targetEntity = A.class)
@Fetch(FetchMode.SELECT)
@JoinColumn(name ="A1", referencedColumnName = "A1" , insertable = false, updatable = false)
public A getaObj() {
return aObj;
}
public void setaObj(A aObj) {
this.aObj = aObj;
}
}
public static
|
B
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/config/AbstractConfig.java
|
{
"start": 20726,
"end": 21119
}
|
class ____ implement
* @param configOverrides Configuration overrides to use.
* @return The list of configured instances
*/
public <T> List<T> getConfiguredInstances(String key, Class<T> t, Map<String, Object> configOverrides) {
return getConfiguredInstances(getList(key), t, configOverrides);
}
/**
* Get a list of configured instances of the given
|
should
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ComparableTypeTest.java
|
{
"start": 2781,
"end": 2862
}
|
interface ____ {}
// BUG: Diagnostic contains: [ComparableType]
static final
|
Foo
|
java
|
micronaut-projects__micronaut-core
|
inject/src/main/java/io/micronaut/context/BeanProvider.java
|
{
"start": 1390,
"end": 7850
}
|
interface ____<T> extends Iterable<T> {
/**
* The get method will materialize an instance of the bean if it is resolvable.
*
* <p>A bean is considered resolvable if it is both unique and present. See {@link #isUnique()} and {@link #isPresent()}.</p>
*
* <p>Note that if the bean is {@link jakarta.inject.Singleton} then multiple calls to this method will return the same instance.</p>
*
* @return A fully-constructed and injected instance of {@link T}.
* @throws io.micronaut.context.exceptions.BeanCreationException If an error occurs during the creation of the bean
* @throws io.micronaut.context.exceptions.NoSuchBeanException if the bean doesn't exist
* @throws io.micronaut.context.exceptions.NonUniqueBeanException if more than one bean matching the current qualifier exists and cannot be resolved unambiguously
*/
@NonNull
T get();
/**
* Convert this provider into a jakarta provider.
* @return The jakarta provider.
* @since 4.5.0
*/
default @NonNull Provider<T> asJakartaProvider() {
return this::get;
}
/**
* Finds a bean for the optionally specified qualifier. Return empty if non-exists.
* @param qualifier The qualifier to use. Can be {@code null} which is equivalent to specifying the default qualifier.
* @return An optional of the bean.
* @since 3.2.0
*/
default Optional<T> find(@Nullable Qualifier<T> qualifier) {
if (isPresent()) {
return Optional.of(get());
} else {
return Optional.empty();
}
}
/**
* Obtains a reference to the {@link io.micronaut.inject.BeanDefinition} if the bean is resolvable.
* @return The {@link io.micronaut.inject.BeanDefinition}
* @throws io.micronaut.context.exceptions.NoSuchBeanException if the bean doesn't exist
* @throws io.micronaut.context.exceptions.NonUniqueBeanException if more than one bean matching the current qualifier exists and cannot be resolved unambiguously
* @throws java.lang.UnsupportedOperationException If the BeanProvider was obtained via other means other than dependency injection
* @since 3.2.0
*/
@NonNull
default BeanDefinition<T> getDefinition() {
throw new UnsupportedOperationException("BeanDefinition information can only be obtained from dependency injected providers");
}
/**
* @see #get()
* @param qualifier The qualifier to use, can be {@code null}.
* @return A fully-constructed and injected instance of {@link T}.
* @since 3.0.0
* @throws io.micronaut.context.exceptions.BeanCreationException If an error occurs during the creation of the bean
* @throws io.micronaut.context.exceptions.NoSuchBeanException if the bean doesn't exist
* @throws io.micronaut.context.exceptions.NonUniqueBeanException if more than one bean matching the current qualifier exists and cannot be resolved unambiguously
*/
@NonNull
default T get(@Nullable Qualifier<T> qualifier) {
return get();
}
@NonNull
@Override
default Iterator<T> iterator() {
return Collections.singletonList(get()).iterator();
}
/**
* <p>
* When called, provides back a Stream of the beans available in this provider. If no beans are found, it returns an empty
* stream.
* </p>
*
* @since 3.0.0
* @return a <code>Stream</code> representing the beans associated with this {@link BeanProvider} object
*/
default Stream<T> stream() {
return StreamSupport.stream(this.spliterator(), false);
}
/**
* <p>Determines if more than one bean matches the specified type and qualifiers.</p>
*
* @since 3.0.0
* @return <code>true</code> if only one bean matches.
*/
default boolean isUnique() {
return true;
}
/**
* <p>Determines if there is a bean that matches the required type and qualifiers.</p>
*
* @since 3.0.0
* @return true if at least one bean matches.
*/
default boolean isPresent() {
return true;
}
/**
* Is the bean resolvable using the {@link #get()} or {@link #ifPresent(Consumer)} methods.
*
* <p>A bean is said to be resolvable when it is both unique (see {@link #isUnique()}) and present (see {@link #isPresent()})</p>
*
* @return True if the bean is resolvable
* @since 3.0.0
*/
default boolean isResolvable() {
return isUnique() && isPresent();
}
/**
* Executes the given logic if the bean is present. Executes {@link #get()} to obtain the bean which may result in a {@link io.micronaut.context.exceptions.NonUniqueBeanException} if the bean is not unique.
*
* @param consumer the consumer
* @since 3.0.0
* @see #isPresent()
* @throws io.micronaut.context.exceptions.NonUniqueBeanException if the bean is not unique
*/
default void ifPresent(@NonNull Consumer<T> consumer) {
if (isPresent()) {
Objects.requireNonNull(consumer, "Consumer cannot be null")
.accept(get());
}
}
/**
* Executes the given logic if the bean is resolvable. See {@link #isResolvable()}.
*
* @param consumer the consumer
* @since 3.0.0
* @see #isResolvable()
*/
default void ifResolvable(@NonNull Consumer<T> consumer) {
if (isResolvable()) {
Objects.requireNonNull(consumer, "Consumer cannot be null")
.accept(get());
}
}
/**
* Allows selecting an alternative bean if the backing bean is not present.
* @param alternative The alternative, can be {@code null}
* @return The bean if present or else the supplied alternative
* @since 3.0.2
*/
default @Nullable T orElse(@Nullable T alternative) {
if (isPresent()) {
return get();
} else {
return alternative;
}
}
/**
* Create an argument for the given type to aid with bean provider lookup.
*
* @param type The type
* @param <T1> The generic type
* @return 3.0.0
*/
@SuppressWarnings({"unchecked", "rawtypes"})
static @NonNull <T1> Argument<BeanProvider<T1>> argumentOf(@NonNull Class<T1> type) {
return (Argument) Argument.of(BeanProvider.class, Objects.requireNonNull(type, "Type cannot be null"));
}
}
|
BeanProvider
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/errors/TextEncodeErrorTest.java
|
{
"start": 1600,
"end": 2061
}
|
class ____ {
@OnTextMessage(outputCodec = BadCodec.class)
Pojo process(Pojo pojo) {
return pojo;
}
@OnError
String encodingError(TextEncodeException e) {
assertTrue(Context.isOnWorkerThread());
return e.getCause().toString() + ":" + e.getEncodedObject().toString();
}
}
@Priority(-1) // Let the JsonTextMessageCodec decode the pojo
@Singleton
public static
|
Echo
|
java
|
spring-projects__spring-boot
|
module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/otlp/OtlpHttpSpanExporterBuilderCustomizer.java
|
{
"start": 1027,
"end": 1244
}
|
interface ____ {
/**
* Customize the {@link OtlpHttpSpanExporterBuilder}.
* @param builder the builder to customize
*/
void customize(OtlpHttpSpanExporterBuilder builder);
}
|
OtlpHttpSpanExporterBuilderCustomizer
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/jdbc/SelectBuilder.java
|
{
"start": 779,
"end": 2341
}
|
class ____ {
private static final ThreadLocal<SQL> localSQL = new ThreadLocal<>();
static {
BEGIN();
}
private SelectBuilder() {
// Prevent Instantiation
}
public static void BEGIN() {
RESET();
}
public static void RESET() {
localSQL.set(new SQL());
}
public static void SELECT(String columns) {
sql().SELECT(columns);
}
public static void SELECT_DISTINCT(String columns) {
sql().SELECT_DISTINCT(columns);
}
public static void FROM(String table) {
sql().FROM(table);
}
public static void JOIN(String join) {
sql().JOIN(join);
}
public static void INNER_JOIN(String join) {
sql().INNER_JOIN(join);
}
public static void LEFT_OUTER_JOIN(String join) {
sql().LEFT_OUTER_JOIN(join);
}
public static void RIGHT_OUTER_JOIN(String join) {
sql().RIGHT_OUTER_JOIN(join);
}
public static void OUTER_JOIN(String join) {
sql().OUTER_JOIN(join);
}
public static void WHERE(String conditions) {
sql().WHERE(conditions);
}
public static void OR() {
sql().OR();
}
public static void AND() {
sql().AND();
}
public static void GROUP_BY(String columns) {
sql().GROUP_BY(columns);
}
public static void HAVING(String conditions) {
sql().HAVING(conditions);
}
public static void ORDER_BY(String columns) {
sql().ORDER_BY(columns);
}
public static String SQL() {
try {
return sql().toString();
} finally {
RESET();
}
}
private static SQL sql() {
return localSQL.get();
}
}
|
SelectBuilder
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java
|
{
"start": 8841,
"end": 27534
}
|
class ____.
*
* @param template must not be {@literal null}.
* @param entityName must not be {@literal null}.
* @return the template with placeholders replaced by the {@literal entityName}. Guaranteed to be not {@literal null}.
*/
public static String getQueryString(String template, String entityName) {
Assert.hasText(entityName, "Entity name must not be null or empty");
return String.format(template, entityName);
}
/**
* Adds {@literal order by} clause to the JPQL query. Uses the first alias to bind the sorting property to.
*
* @param query the query string to which sorting is applied
* @param sort the sort specification to apply.
* @return the modified query string.
*/
public static String applySorting(String query, Sort sort) {
return applySorting(query, sort, detectAlias(query));
}
/**
* Adds {@literal order by} clause to the JPQL query.
*
* @param query the query string to which sorting is applied. Must not be {@literal null} or empty.
* @param sort the sort specification to apply.
* @param alias the alias to be used in the order by clause. May be {@literal null} or empty.
* @return the modified query string.
*/
public static String applySorting(String query, Sort sort, @Nullable String alias) {
Assert.hasText(query, "Query must not be null or empty");
if (sort.isUnsorted()) {
return query;
}
StringBuilder builder = new StringBuilder(query);
if (hasOrderByClause(query)) {
builder.append(", ");
} else {
builder.append(" order by ");
}
Set<String> joinAliases = getOuterJoinAliases(query);
Set<String> selectionAliases = getFunctionAliases(query);
selectionAliases.addAll(getFieldAliases(query));
String orderClauses = sort.stream().map(order -> getOrderClause(joinAliases, selectionAliases, alias, order))
.collect(Collectors.joining(", "));
builder.append(orderClauses);
return builder.toString();
}
/**
* Returns {@code true} if the query has {@code order by} clause. The query has {@code order by} clause if there is an
* {@code order by} which is not part of window clause.
*
* @param query the analysed query string
* @return {@code true} if the query has {@code order by} clause, {@code false} otherwise
*/
private static boolean hasOrderByClause(String query) {
return countOccurrences(ORDER_BY, query) > countOccurrences(ORDER_BY_IN_WINDOW_OR_SUBSELECT, query);
}
/**
* Counts the number of occurrences of the pattern in the string
*
* @param pattern regex with a group to match
* @param string analysed string
* @return the number of occurrences of the pattern in the string
*/
private static int countOccurrences(Pattern pattern, String string) {
Matcher matcher = pattern.matcher(string);
int occurrences = 0;
while (matcher.find()) {
occurrences++;
}
return occurrences;
}
/**
* Returns the order clause for the given {@link Order}. Will prefix the clause with the given alias if the referenced
* property refers to a join alias, i.e. starts with {@code $alias.}.
*
* @param joinAliases the join aliases of the original query. Must not be {@literal null}.
* @param alias the alias for the root entity. May be {@literal null}.
* @param order the order object to build the clause for. Must not be {@literal null}.
* @return a String containing an order clause. Guaranteed to be not {@literal null}.
*/
private static String getOrderClause(Set<String> joinAliases, Set<String> selectionAlias, @Nullable String alias,
Order order) {
String property = order.getProperty();
checkSortExpression(order);
if (selectionAlias.contains(property)) {
return String.format("%s %s", //
order.isIgnoreCase() ? String.format("lower(%s)", property) : property, //
toJpaDirection(order));
}
boolean qualifyReference = !property.contains("("); // ( indicates a function
for (String joinAlias : joinAliases) {
if (property.startsWith(joinAlias.concat("."))) {
qualifyReference = false;
break;
}
}
String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
: property;
String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;
return String.format("%s %s", wrapped, toJpaDirection(order));
}
/**
* Returns the aliases used for {@code left (outer) join}s.
*
* @param query a query string to extract the aliases of joins from. Must not be {@literal null}.
* @return a {@literal Set} of aliases used in the query. Guaranteed to be not {@literal null}.
*/
static Set<String> getOuterJoinAliases(String query) {
Set<String> result = new HashSet<>();
Matcher matcher = JOIN_PATTERN.matcher(query);
while (matcher.find()) {
String alias = matcher.group(QUERY_JOIN_ALIAS_GROUP_INDEX);
if (StringUtils.hasText(alias)) {
result.add(alias);
}
}
return result;
}
/**
* Returns the aliases used for fields in the query.
*
* @param query a {@literal String} containing a query. Must not be {@literal null}.
* @return a {@literal Set} containing all found aliases. Guaranteed to be not {@literal null}.
*/
static Set<String> getFieldAliases(String query) {
Set<String> result = new HashSet<>();
Matcher matcher = FIELD_ALIAS_PATTERN.matcher(query);
while (matcher.find()) {
String alias = matcher.group(1);
if (StringUtils.hasText(alias)) {
result.add(alias);
}
}
return result;
}
/**
* Returns the aliases used for aggregate functions like {@code SUM, COUNT, ...}.
*
* @param query a {@literal String} containing a query. Must not be {@literal null}.
* @return a {@literal Set} containing all found aliases. Guaranteed to be not {@literal null}.
*/
static Set<String> getFunctionAliases(String query) {
Set<String> result = new HashSet<>();
Matcher matcher = FUNCTION_PATTERN.matcher(query);
while (matcher.find()) {
String alias = matcher.group(1);
if (StringUtils.hasText(alias)) {
result.add(alias);
}
}
return result;
}
private static String toJpaDirection(Order order) {
String direction = order.getDirection().name().toLowerCase(Locale.US);
return switch (order.getNullHandling()) {
case NATIVE -> direction;
case NULLS_FIRST -> direction + " nulls first";
case NULLS_LAST -> direction + " nulls last";
};
}
/**
* Resolves the alias for the entity to be retrieved from the given JPA query.
*
* @param query must not be {@literal null}.
* @return Might return {@literal null}.
*/
static @Nullable String detectAlias(String query) {
String alias = null;
Matcher matcher = ALIAS_MATCH.matcher(removeSubqueries(query));
while (matcher.find()) {
alias = matcher.group(2);
}
return alias;
}
/**
* Remove subqueries from the query, in order to identify the correct alias in order by clauses. If the entire query
* is surrounded by parenthesis, the outermost parenthesis are not removed.
*
* @param query
* @return query with all subqueries removed.
*/
static String removeSubqueries(String query) {
if (!StringUtils.hasText(query)) {
return query;
}
List<Integer> opens = new ArrayList<>();
List<Integer> closes = new ArrayList<>();
List<Boolean> closeMatches = new ArrayList<>();
for (int i = 0; i < query.length(); i++) {
char c = query.charAt(i);
if (c == '(') {
opens.add(i);
} else if (c == ')') {
closes.add(i);
closeMatches.add(Boolean.FALSE);
}
}
StringBuilder sb = new StringBuilder(query);
boolean startsWithParen = STARTS_WITH_PAREN.matcher(query).find();
for (int i = opens.size() - 1; i >= (startsWithParen ? 1 : 0); i--) {
Integer open = opens.get(i);
Integer close = findClose(open, closes, closeMatches) + 1;
if (close > open) {
String subquery = sb.substring(open, close);
Matcher matcher = PARENS_TO_REMOVE.matcher(subquery);
if (matcher.find()) {
sb.replace(open, close, new String(new char[close - open]).replace('\0', ' '));
}
}
}
return sb.toString();
}
private static Integer findClose(final Integer open, final List<Integer> closes, final List<Boolean> closeMatches) {
for (int i = 0; i < closes.size(); i++) {
int close = closes.get(i);
if (close > open && !closeMatches.get(i)) {
closeMatches.set(i, Boolean.TRUE);
return close;
}
}
return -1;
}
/**
* Creates a where-clause referencing the given entities and appends it to the given query string. Binds the given
* entities to the query.
*
* @param <T> type of the entities.
* @param queryString must not be {@literal null}.
* @param entities must not be {@literal null}.
* @param entityManager must not be {@literal null}.
* @return Guaranteed to be not {@literal null}.
*/
public static <T> Query applyAndBind(String queryString, Iterable<T> entities, EntityManager entityManager) {
return applyAndBind(queryString, entities, entityManager, PersistenceProvider.fromEntityManager(entityManager));
}
/**
* Creates a where-clause referencing the given entities and appends it to the given query string. Binds the given
* entities to the query.
*
* @param <T> type of the entities.
* @param queryString must not be {@literal null}.
* @param entities must not be {@literal null}.
* @param entityManager must not be {@literal null}.
* @return Guaranteed to be not {@literal null}.
*/
static <T> Query applyAndBind(String queryString, Iterable<T> entities, EntityManager entityManager,
PersistenceProvider persistenceProvider) {
Assert.notNull(queryString, "Querystring must not be null");
Assert.notNull(entities, "Iterable of entities must not be null");
Assert.notNull(entityManager, "EntityManager must not be null");
Iterator<T> iterator = entities.iterator();
if (!iterator.hasNext()) {
return entityManager.createQuery(queryString);
}
if (persistenceProvider == PersistenceProvider.HIBERNATE) {
String alias = detectAlias(queryString);
Query query = entityManager.createQuery("%s where %s IN (?1)".formatted(queryString, alias));
query.setParameter(1, entities instanceof Collection<T> ? entities : Streamable.of(entities).toList());
return query;
}
return applyWhereEqualsAndBind(queryString, entities, entityManager, iterator);
}
private static Query applyWhereEqualsAndBind(String queryString, Iterable<?> entities, EntityManager entityManager,
Iterator<?> iterator) {
String alias = detectAlias(queryString);
StringBuilder builder = new StringBuilder(queryString);
builder.append(" where");
int i = 0;
while (iterator.hasNext()) {
iterator.next();
builder.append(String.format(" %s = ?%d", alias, ++i));
if (iterator.hasNext()) {
builder.append(" or");
}
}
Query query = entityManager.createQuery(builder.toString());
iterator = entities.iterator();
i = 0;
while (iterator.hasNext()) {
query.setParameter(++i, iterator.next());
}
return query;
}
/**
* Creates a count projected query from the given original query.
*
* @param originalQuery must not be {@literal null} or empty.
* @return Guaranteed to be not {@literal null}.
*/
static String createCountQueryFor(String originalQuery) {
return createCountQueryFor(originalQuery, null);
}
/**
* Creates a count projected query from the given original query.
*
* @param originalQuery must not be {@literal null}.
* @param countProjection may be {@literal null}.
* @return a query String to be used a count query for pagination. Guaranteed to be not {@literal null}.
* @since 1.6
*/
static String createCountQueryFor(String originalQuery, @Nullable String countProjection) {
return createCountQueryFor(originalQuery, countProjection, false);
}
/**
* Creates a count projected query from the given original query.
*
* @param originalQuery must not be {@literal null}.
* @param countProjection may be {@literal null}.
* @param nativeQuery whether the underlying query is a native query.
* @return a query String to be used a count query for pagination. Guaranteed to be not {@literal null}.
* @since 2.7.8
*/
public static String createCountQueryFor(String originalQuery, @Nullable String countProjection,
boolean nativeQuery) {
Assert.hasText(originalQuery, "OriginalQuery must not be null or empty");
Matcher matcher = COUNT_MATCH.matcher(originalQuery);
String countQuery;
if (countProjection == null) {
String variable = matcher.matches() ? matcher.group(VARIABLE_NAME_GROUP_INDEX) : null;
boolean useVariable = StringUtils.hasText(variable) //
&& !variable.startsWith("new") // select [new com.example.User...
&& !variable.startsWith(" new") // select distinct[ new com.example.User...
&& !variable.startsWith("count(") // select [count(...
&& !variable.contains(",");
String complexCountValue = matcher.matches() && StringUtils.hasText(matcher.group(COMPLEX_COUNT_FIRST_INDEX))
? COMPLEX_COUNT_VALUE
: COMPLEX_COUNT_LAST_VALUE;
String replacement = useVariable ? SIMPLE_COUNT_VALUE : complexCountValue;
if (variable != null && (nativeQuery && (variable.contains(",") || "*".equals(variable)))) {
replacement = "1";
} else {
String alias = QueryUtils.detectAlias(originalQuery);
if ("*".equals(variable) && alias != null) {
replacement = alias;
}
}
countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, replacement));
} else {
countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, countProjection));
}
return ORDER_BY_PART.matcher(countQuery).replaceFirst("");
}
/**
* Returns whether the given {@link Query} contains named parameters.
*
* @param query Must not be {@literal null}.
* @return whether the given {@link Query} contains named parameters.
*/
public static boolean hasNamedParameter(Query query) {
Assert.notNull(query, "Query must not be null");
for (Parameter<?> parameter : query.getParameters()) {
String name = parameter.getName();
// Hibernate 3 specific hack as it returns the index as String for the name.
if (name != null && NO_DIGITS.matcher(name).find()) {
return true;
}
}
return false;
}
/**
* Turns the given {@link Sort} into {@link jakarta.persistence.criteria.Order}s.
*
* @param sort the {@link Sort} instance to be transformed into JPA {@link jakarta.persistence.criteria.Order}s.
* @param from must not be {@literal null}.
* @param cb must not be {@literal null}.
* @return a {@link List} of {@link jakarta.persistence.criteria.Order}s.
*/
public static List<jakarta.persistence.criteria.Order> toOrders(Sort sort, From<?, ?> from, CriteriaBuilder cb) {
if (sort.isUnsorted()) {
return Collections.emptyList();
}
Assert.notNull(from, "From must not be null");
Assert.notNull(cb, "CriteriaBuilder must not be null");
List<jakarta.persistence.criteria.Order> orders = new ArrayList<>();
for (Order order : sort) {
orders.add(toJpaOrder(order, from, cb));
}
return orders;
}
/**
* Returns whether the given JPQL query contains a constructor expression.
*
* @param query must not be {@literal null} or empty.
* @return whether the given JPQL query contains a constructor expression.
* @since 1.10
*/
public static boolean hasConstructorExpression(String query) {
Assert.hasText(query, "Query must not be null or empty");
return CONSTRUCTOR_EXPRESSION.matcher(query).find();
}
/**
* Returns the projection part of the query, i.e. everything between {@code select} and {@code from}.
*
* @param query must not be {@literal null} or empty.
* @return the projection part of the query.
* @since 1.10.2
*/
public static String getProjection(String query) {
Assert.hasText(query, "Query must not be null or empty");
Matcher matcher = PROJECTION_CLAUSE.matcher(query);
String projection = matcher.find() ? matcher.group(1) : "";
return projection.trim();
}
/**
* Creates a criteria API {@link jakarta.persistence.criteria.Order} from the given {@link Order}.
*
* @param order the order to transform into a JPA {@link jakarta.persistence.criteria.Order}
* @param from the {@link From} the {@link Order} expression is based on
* @param cb the {@link CriteriaBuilder} to build the {@link jakarta.persistence.criteria.Order} with
* @return Guaranteed to be not {@literal null}.
*/
@SuppressWarnings("unchecked")
private static jakarta.persistence.criteria.Order toJpaOrder(Order order, From<?, ?> from, CriteriaBuilder cb) {
Expression<?> expression;
checkSortExpression(order);
if (order instanceof JpaOrder jpaOrder && jpaOrder.isUnsafe()) {
expression = new HqlOrderExpressionVisitor(cb, from, QueryUtils::toExpressionRecursively)
.createCriteriaExpression(order);
} else {
PropertyPath property = PropertyPath.from(order.getProperty(), from.getJavaType());
expression = toExpressionRecursively(from, property);
}
Nulls nulls = toNulls(order.getNullHandling());
if (order.isIgnoreCase() && String.class.equals(expression.getJavaType())) {
Expression<String> upper = cb.lower((Expression<String>) expression);
return order.isAscending() ? cb.asc(upper, nulls) : cb.desc(upper, nulls);
} else {
return order.isAscending() ? cb.asc(expression, nulls) : cb.desc(expression, nulls);
}
}
private static Nulls toNulls(Sort.NullHandling nullHandling) {
return switch (nullHandling) {
case NULLS_LAST -> Nulls.LAST;
case NULLS_FIRST -> Nulls.FIRST;
case NATIVE -> Nulls.NONE;
};
}
/**
* Check any given {@link JpaOrder#isUnsafe()} order for presence of at least one property offending the
* {@link #PUNCTATION_PATTERN} and throw an {@link Exception} indicating potential unsafe order by expression.
*
* @param order
*/
public static void checkSortExpression(Order order) {
if (order instanceof JpaOrder jpaOrder && jpaOrder.isUnsafe()) {
return;
}
if (PUNCTATION_PATTERN.matcher(order.getProperty()).find()) {
throw new InvalidDataAccessApiUsageException(String.format(UNSAFE_PROPERTY_REFERENCE, order));
}
}
static <T> Expression<T> toExpressionRecursively(From<?, ?> from, PropertyPath property) {
return toExpressionRecursively(from, property, false);
}
public static <T> Expression<T> toExpressionRecursively(From<?, ?> from, PropertyPath property,
boolean isForSelection) {
return FromExpressionFactory.INSTANCE.toExpressionRecursively(from, property, isForSelection, false);
}
/**
* Expression factory to create {@link Expression}s from a CriteriaBuilder {@link From}.
*
* @since 4.0
*/
static
|
name
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/maps/Maps_assertHasEntrySatisfying_with_key_and_value_conditions_Test.java
|
{
"start": 1466,
"end": 4848
}
|
class ____ extends MapsBaseTest {
private final Condition<String> isColor = new Condition<>("is color condition") {
@Override
public boolean matches(String value) {
return "color".equals(value);
}
};
private final Condition<String> isGreen = new Condition<>("green color condition") {
@Override
public boolean matches(String value) {
return "green".equals(value);
}
};
private final Condition<Object> isAge = new Condition<>() {
@Override
public boolean matches(Object value) {
return "age".equals(value);
}
};
private final Condition<Object> isBlack = new Condition<>("black color condition") {
@Override
public boolean matches(Object value) {
return "black".equals(value);
}
};
@Test
void should_fail_if_key_condition_is_null() {
assertThatNullPointerException().isThrownBy(() -> maps.assertHasEntrySatisfyingConditions(INFO, actual, null,
isGreen))
.withMessage("The condition to evaluate for entries key should not be null");
}
@Test
void should_fail_if_value_condition_is_null() {
assertThatNullPointerException().isThrownBy(() -> maps.assertHasEntrySatisfyingConditions(INFO, actual,
isColor, null))
.withMessage("The condition to evaluate for entries value should not be null");
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasEntrySatisfyingConditions(INFO, null,
isColor, isGreen))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_does_not_contain_any_entry_matching_the_given_key_condition() {
AssertionInfo info = INFO;
Throwable error = catchThrowable(() -> maps.assertHasEntrySatisfyingConditions(info, actual, isAge, isGreen));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainEntry(actual, isAge, isGreen));
}
@Test
void should_fail_if_actual_does_not_contain_any_entry_matching_the_given_value_condition() {
AssertionInfo info = INFO;
Throwable error = catchThrowable(() -> maps.assertHasEntrySatisfyingConditions(info, actual, isColor, isBlack));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainEntry(actual, isColor, isBlack));
}
@Test
void should_fail_if_actual_does_not_contain_any_entry_matching_both_given_key_and_value_conditions() {
AssertionInfo info = INFO;
Throwable error = catchThrowable(() -> maps.assertHasEntrySatisfyingConditions(info, actual, isAge, isBlack));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainEntry(actual, isAge, isBlack));
}
@Test
void should_pass_if_actual_contains_an_entry_matching_both_key_and_value_conditions() {
maps.assertHasEntrySatisfyingConditions(INFO, actual, isColor, isGreen);
}
}
|
Maps_assertHasEntrySatisfying_with_key_and_value_conditions_Test
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/RLockAsync.java
|
{
"start": 688,
"end": 759
}
|
interface ____ Lock object
*
* @author Nikita Koksharov
*
*/
public
|
for
|
java
|
alibaba__nacos
|
core/src/main/java/com/alibaba/nacos/core/persistence/DerbySnapshotOperation.java
|
{
"start": 2139,
"end": 7504
}
|
class ____ implements SnapshotOperation {
private static final Logger LOGGER = LoggerFactory.getLogger(DerbySnapshotOperation.class);
private static final String DERBY_SNAPSHOT_SAVE = DerbySnapshotOperation.class.getSimpleName() + ".SAVE";
private static final String DERBY_SNAPSHOT_LOAD = DerbySnapshotOperation.class.getSimpleName() + ".LOAD";
private final String backupSql = "CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)";
private final String snapshotDir = "derby_data";
private final String snapshotArchive = "derby_data.zip";
private final String derbyBaseDir = Paths.get(EnvUtil.getNacosHome(), "data", PersistenceConstant.DERBY_BASE_DIR)
.toString();
private final String restoreDB = "jdbc:derby:" + derbyBaseDir;
private final String checkSumKey = "checkSum";
private final ReentrantReadWriteLock.WriteLock writeLock;
public DerbySnapshotOperation(ReentrantReadWriteLock.WriteLock writeLock) {
this.writeLock = writeLock;
}
@Override
public void onSnapshotSave(Writer writer, BiConsumer<Boolean, Throwable> callFinally) {
PersistenceExecutor.executeSnapshot(() -> {
TimerContext.start(DERBY_SNAPSHOT_SAVE);
final Lock lock = writeLock;
lock.lock();
try {
final String writePath = writer.getPath();
final String parentPath = Paths.get(writePath, snapshotDir).toString();
DiskUtils.deleteDirectory(parentPath);
DiskUtils.forceMkdir(parentPath);
doDerbyBackup(parentPath);
final String outputFile = Paths.get(writePath, snapshotArchive).toString();
final Checksum checksum = new CRC64();
DiskUtils.compress(writePath, snapshotDir, outputFile, checksum);
DiskUtils.deleteDirectory(parentPath);
final LocalFileMeta meta = new LocalFileMeta();
meta.append(checkSumKey, Long.toHexString(checksum.getValue()));
callFinally.accept(writer.addFile(snapshotArchive, meta), null);
} catch (Throwable t) {
LOGGER.error("Fail to compress snapshot, path={}, file list={}, {}.", writer.getPath(),
writer.listFiles(), t);
callFinally.accept(false, t);
} finally {
lock.unlock();
TimerContext.end(DERBY_SNAPSHOT_SAVE, LOGGER);
}
});
}
@Override
public boolean onSnapshotLoad(Reader reader) {
final String readerPath = reader.getPath();
final String sourceFile = Paths.get(readerPath, snapshotArchive).toString();
TimerContext.start(DERBY_SNAPSHOT_LOAD);
final Lock lock = writeLock;
lock.lock();
try {
final Checksum checksum = new CRC64();
DiskUtils.decompress(sourceFile, readerPath, checksum);
LocalFileMeta fileMeta = reader.getFileMeta(snapshotArchive);
if (fileMeta.getFileMeta().containsKey(checkSumKey)) {
if (!Objects.equals(Long.toHexString(checksum.getValue()), fileMeta.get(checkSumKey))) {
throw new IllegalArgumentException("Snapshot checksum failed");
}
}
final String loadPath = Paths.get(readerPath, snapshotDir, PersistenceConstant.DERBY_BASE_DIR).toString();
LOGGER.info("snapshot load from : {}, and copy to : {}", loadPath, derbyBaseDir);
doDerbyRestoreFromBackup(() -> {
final File srcDir = new File(loadPath);
final File destDir = new File(derbyBaseDir);
DiskUtils.copyDirectory(srcDir, destDir);
LOGGER.info("Complete database recovery");
return null;
});
DiskUtils.deleteDirectory(loadPath);
NotifyCenter.publishEvent(DerbyLoadEvent.INSTANCE);
return true;
} catch (final Throwable t) {
LOGGER.error("Fail to load snapshot, path={}, file list={}, {}.", readerPath, reader.listFiles(), t);
return false;
} finally {
lock.unlock();
TimerContext.end(DERBY_SNAPSHOT_LOAD, LOGGER);
}
}
private void doDerbyBackup(String backupDirectory) throws Exception {
DataSourceService sourceService = DynamicDataSource.getInstance().getDataSource();
DataSource dataSource = sourceService.getJdbcTemplate().getDataSource();
try (Connection holder = Objects.requireNonNull(dataSource, "dataSource").getConnection()) {
CallableStatement cs = holder.prepareCall(backupSql);
cs.setString(1, backupDirectory);
cs.execute();
}
}
private void doDerbyRestoreFromBackup(Callable<Void> callable) throws Exception {
DataSourceService sourceService = DynamicDataSource.getInstance().getDataSource();
LocalDataSourceServiceImpl localDataSourceService = (LocalDataSourceServiceImpl) sourceService;
localDataSourceService.restoreDerby(restoreDB, callable);
}
}
|
DerbySnapshotOperation
|
java
|
square__javapoet
|
src/test/java/com/squareup/javapoet/TypeSpecTest.java
|
{
"start": 37009,
"end": 37268
}
|
class ____ {\n"
+ " Top internalTop;\n"
+ "\n"
+ " Middle.Bottom internalBottom;\n"
+ "\n"
+ " com.squareup.donuts.Top externalTop;\n"
+ "\n"
+ " Bottom externalBottom;\n"
+ "\n"
+ "
|
Top
|
java
|
apache__spark
|
sql/catalyst/src/main/java/org/apache/spark/sql/connector/expressions/filter/Or.java
|
{
"start": 1084,
"end": 1344
}
|
class ____ extends Predicate {
public Or(Predicate left, Predicate right) {
super("OR", new Predicate[]{left, right});
}
public Predicate left() { return (Predicate) children()[0]; }
public Predicate right() { return (Predicate) children()[1]; }
}
|
Or
|
java
|
apache__flink
|
flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermark.java
|
{
"start": 1060,
"end": 2088
}
|
class ____ implements Watermark {
private static final long serialVersionUID = 1L;
private final long value;
private final String identifier;
public LongWatermark(long value, String identifier) {
this.value = value;
this.identifier = identifier;
}
public long getValue() {
return value;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LongWatermark that = (LongWatermark) o;
return value == that.value && Objects.equals(identifier, that.identifier);
}
@Override
public int hashCode() {
return Objects.hash(value, identifier);
}
@Override
public String toString() {
return "LongWatermark{" + "value=" + value + ", identifier='" + identifier + '\'' + '}';
}
}
|
LongWatermark
|
java
|
dropwizard__dropwizard
|
dropwizard-jdbi3/src/test/java/io/dropwizard/jdbi3/JdbiHealthCheckTest.java
|
{
"start": 781,
"end": 2921
}
|
class ____ {
private static final String VALIDATION_QUERY = "select 1";
private Jdbi jdbi;
private Handle handle;
private Connection connection;
private ExecutorService executorService;
@BeforeEach
void setup() {
jdbi = mock(Jdbi.class);
handle = mock(Handle.class);
connection = mock(Connection.class);
when(jdbi.open()).thenReturn(handle);
when(handle.getConnection()).thenReturn(connection);
executorService = Executors.newSingleThreadExecutor();
}
@AfterEach
void teardown() {
executorService.shutdown();
}
@Test
void testNoTimeoutReturnsHealthy() throws Exception {
when(handle.execute(VALIDATION_QUERY)).thenReturn(0);
HealthCheck.Result result = healthCheck(VALIDATION_QUERY).check();
assertThat(result.isHealthy()).isTrue();
}
@Test
void tesHealthyAfterWhenMissingValidationQuery() throws Exception {
when(connection.isValid(anyInt())).thenReturn(true);
HealthCheck.Result result = healthCheck().check();
assertThat(result.isHealthy()).isTrue();
verify(connection).isValid(anyInt());
}
@Test
void testItTimesOutProperly() throws Exception {
when(handle.execute(VALIDATION_QUERY)).thenAnswer((Answer<Integer>) invocation -> {
TimeUnit.SECONDS.sleep(10);
return null;
});
HealthCheck.Result result = healthCheck(VALIDATION_QUERY).check();
assertThat(result.isHealthy()).isFalse();
}
@Test
void testUnhealthyWhenMissingValidationQuery() throws Exception {
HealthCheck.Result result = healthCheck().check();
assertThat(result.isHealthy()).isFalse();
verify(connection).isValid(anyInt());
}
private JdbiHealthCheck healthCheck() {
return healthCheck(null);
}
private JdbiHealthCheck healthCheck(@Nullable String validationQuery) {
return new JdbiHealthCheck(executorService,
Duration.milliseconds(100),
jdbi,
Optional.ofNullable(validationQuery));
}
}
|
JdbiHealthCheckTest
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/main/java/org/apache/log4j/xml/XmlConfiguration.java
|
{
"start": 11773,
"end": 11874
}
|
class ____ to be implemented
* by created class
* @return created
|
expected
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProviderTests.java
|
{
"start": 6945,
"end": 7093
}
|
class ____ {
@ConstructorBinding
OneConstructorWithConstructorBinding(String name, int age) {
}
}
static
|
OneConstructorWithConstructorBinding
|
java
|
apache__flink
|
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/NFA.java
|
{
"start": 20781,
"end": 22025
}
|
class ____<T> {
private List<StateTransition<T>> edges = new ArrayList<>();
private final State<T> currentState;
private int totalTakeBranches = 0;
private int totalIgnoreBranches = 0;
OutgoingEdges(final State<T> currentState) {
this.currentState = currentState;
}
void add(StateTransition<T> edge) {
if (!isSelfIgnore(edge)) {
if (edge.getAction() == StateTransitionAction.IGNORE) {
totalIgnoreBranches++;
} else if (edge.getAction() == StateTransitionAction.TAKE) {
totalTakeBranches++;
}
}
edges.add(edge);
}
int getTotalIgnoreBranches() {
return totalIgnoreBranches;
}
int getTotalTakeBranches() {
return totalTakeBranches;
}
List<StateTransition<T>> getEdges() {
return edges;
}
private boolean isSelfIgnore(final StateTransition<T> edge) {
return isEquivalentState(edge.getTargetState(), currentState)
&& edge.getAction() == StateTransitionAction.IGNORE;
}
}
/**
* Helper
|
OutgoingEdges
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/bounds/SourceTypeIsBoundedTypeVarMapper.java
|
{
"start": 361,
"end": 797
}
|
interface ____ {
SourceTypeIsBoundedTypeVarMapper INSTANCE = Mappers.getMapper( SourceTypeIsBoundedTypeVarMapper.class );
Target sourceToTarget(Source source);
@SuppressWarnings( "unchecked" )
default <T extends NestedBase> T map(String in, @TargetType Class<T> clz) {
if ( clz == Nested.class ) {
return (T) new Nested( in );
}
return null;
}
|
SourceTypeIsBoundedTypeVarMapper
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java
|
{
"start": 3299,
"end": 3610
}
|
interface ____ {
default boolean isCacheHit() {
return !isCacheMiss();
}
boolean isCacheMiss();
void setCacheMiss();
default String greet() {
return greet("World");
}
default String greet(String name) {
setCacheMiss();
return String.format("Hello %s!", name);
}
}
static
|
Greeter
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/internal/IntArrays.java
|
{
"start": 1127,
"end": 18369
}
|
class ____ {
private static final IntArrays INSTANCE = new IntArrays();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static IntArrays instance() {
return INSTANCE;
}
private Arrays arrays = Arrays.instance();
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
Failures failures = Failures.instance();
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
IntArrays() {
this(StandardComparisonStrategy.instance());
}
public IntArrays(ComparisonStrategy comparisonStrategy) {
setArrays(new Arrays(comparisonStrategy));
}
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
public void setArrays(Arrays arrays) {
this.arrays = arrays;
}
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
public Comparator<?> getComparator() {
return arrays.getComparator();
}
/**
* Asserts that the given array is {@code null} or empty.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is not {@code null} *and* contains one or more elements.
*/
public void assertNullOrEmpty(AssertionInfo info, int[] actual) {
arrays.assertNullOrEmpty(info, failures, actual);
}
/**
* Asserts that the given array is empty.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array is not empty.
*/
public void assertEmpty(AssertionInfo info, int[] actual) {
arrays.assertEmpty(info, failures, actual);
}
/**
* Asserts that the given array is not empty.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array is empty.
*/
public void assertNotEmpty(AssertionInfo info, int[] actual) {
arrays.assertNotEmpty(info, failures, actual);
}
/**
* Asserts that the number of elements in the given array is equal to the expected one.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param expectedSize the expected size of {@code actual}.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is different than the expected one.
*/
public void assertHasSize(AssertionInfo info, int[] actual, int expectedSize) {
arrays.assertHasSize(info, actual, expectedSize);
}
/**
* Asserts that the number of elements in the given array is greater than the given boundary.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not greater than the boundary.
*/
public void assertHasSizeGreaterThan(AssertionInfo info, int[] actual, int boundary) {
arrays.assertHasSizeGreaterThan(info, actual, boundary);
}
/**
* Asserts that the number of elements in the given array is greater than or equal to the given boundary.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not greater than or equal to the boundary.
*/
public void assertHasSizeGreaterThanOrEqualTo(AssertionInfo info, int[] actual, int boundary) {
arrays.assertHasSizeGreaterThanOrEqualTo(info, actual, boundary);
}
/**
* Asserts that the number of elements in the given array is less than the given boundary.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not less than the boundary.
*/
public void assertHasSizeLessThan(AssertionInfo info, int[] actual, int boundary) {
arrays.assertHasSizeLessThan(info, actual, boundary);
}
/**
* Asserts that the number of elements in the given array is less than or equal to the given boundary.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param boundary the given value to compare the size of {@code actual} to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not less than or equal to the boundary.
*/
public void assertHasSizeLessThanOrEqualTo(AssertionInfo info, int[] actual, int boundary) {
arrays.assertHasSizeLessThanOrEqualTo(info, actual, boundary);
}
/**
* Asserts that the number of elements in the given array is between the given lower and higher boundary (inclusive).
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param lowerBoundary the lower boundary compared to which actual size should be greater than or equal to.
* @param higherBoundary the higher boundary compared to which actual size should be less than or equal to.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the number of elements in the given array is not between the boundaries.
*/
public void assertHasSizeBetween(AssertionInfo info, int[] actual, int lowerBoundary, int higherBoundary) {
arrays.assertHasSizeBetween(info, actual, lowerBoundary, higherBoundary);
}
/**
* Assert that the actual array has the same size as the other {@code Iterable}.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param other the group to compare
* @throws AssertionError if the actual group is {@code null}.
* @throws AssertionError if the other group is {@code null}.
* @throws AssertionError if the actual group does not have the same size.
*/
public void assertHasSameSizeAs(AssertionInfo info, int[] actual, Iterable<?> other) {
arrays.assertHasSameSizeAs(info, actual, other);
}
/**
* Assert that the actual array has the same size as the other array.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param other the group to compare
* @throws AssertionError if the actual group is {@code null}.
* @throws AssertionError if the other group is {@code null}.
* @throws AssertionError if the actual group does not have the same size.
*/
public void assertHasSameSizeAs(AssertionInfo info, int[] actual, Object[] other) {
arrays.assertHasSameSizeAs(info, actual, other);
}
/**
* Asserts that the given array contains the given values, in any order.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param values the values that are expected to be in the given array.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array does not contain the given values.
*/
public void assertContains(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContains(info, failures, actual, values);
}
/**
* Verifies that the given array contains the given value at the given index.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param value the value to look for.
* @param index the index where the value should be stored in the given array.
* @throws AssertionError if the given array is {@code null} or empty.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of
* the given array.
* @throws AssertionError if the given array does not contain the given value at the given index.
*/
public void assertContains(AssertionInfo info, int[] actual, int value, Index index) {
arrays.assertContains(info, failures, actual, value, index);
}
/**
* Verifies that the given array does not contain the given value at the given index.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param value the value to look for.
* @param index the index where the value should be stored in the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws AssertionError if the given array contains the given value at the given index.
*/
public void assertDoesNotContain(AssertionInfo info, int[] actual, int value, Index index) {
arrays.assertDoesNotContain(info, failures, actual, value, index);
}
/**
* Asserts that the given array contains only the given values and nothing else, in any order.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param values the values that are expected to be in the given array.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array does not contain the given values or if the given array contains values
* that are not in the given array.
*/
public void assertContainsOnly(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContainsOnly(info, failures, actual, values);
}
public void assertContainsExactly(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContainsExactly(info, failures, actual, values);
}
public void assertContainsExactlyInAnyOrder(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContainsExactlyInAnyOrder(info, failures, actual, values);
}
/**
* Asserts that the given array contains only once the given values.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param values the values that are expected to be in the given array.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array does not contain the given values or if the given array contains more
* than once values.
*/
public void assertContainsOnlyOnce(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContainsOnlyOnce(info, failures, actual, values);
}
/**
* Verifies that the given array contains the given sequence of values, without any other values between them.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param sequence the sequence of values to look for.
* @throws AssertionError if the given array is {@code null}.
* @throws NullPointerException if the given sequence is {@code null}.
* @throws IllegalArgumentException if the given sequence is empty.
* @throws AssertionError if the given array does not contain the given sequence of values.
*/
public void assertContainsSequence(AssertionInfo info, int[] actual, int[] sequence) {
arrays.assertContainsSequence(info, failures, actual, sequence);
}
/**
* Verifies that the given array contains the given subsequence of values (possibly with other values between them).
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param subsequence the subsequence of values to look for.
* @throws AssertionError if the given array is {@code null}.
* @throws NullPointerException if the given subsequence is {@code null}.
* @throws IllegalArgumentException if the given subsequence is empty.
* @throws AssertionError if the given array does not contain the given subsequence of values.
*/
public void assertContainsSubsequence(AssertionInfo info, int[] actual, int[] subsequence) {
arrays.assertContainsSubsequence(info, failures, actual, subsequence);
}
/**
* Asserts that the given array does not contain the given values.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param values the values that are expected not to be in the given array.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array contains any of given values.
*/
public void assertDoesNotContain(AssertionInfo info, int[] actual, int[] values) {
arrays.assertDoesNotContain(info, failures, actual, values);
}
/**
* Asserts that the given array does not have duplicate values.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @throws NullPointerException if the array of values is {@code null}.
* @throws IllegalArgumentException if the array of values is empty.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array contains duplicate values.
*/
public void assertDoesNotHaveDuplicates(AssertionInfo info, int[] actual) {
arrays.assertDoesNotHaveDuplicates(info, failures, actual);
}
/**
* Verifies that the given array starts with the given sequence of values, without any other values between them.
* Similar to <code>{@link #assertContainsSequence(AssertionInfo, int[], int[])}</code>, but it also verifies that the
* first element in the sequence is also the first element of the given array.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param sequence the sequence of values to look for.
* @throws NullPointerException if the given argument is {@code null}.
* @throws IllegalArgumentException if the given argument is an empty array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array does not start with the given sequence of values.
*/
public void assertStartsWith(AssertionInfo info, int[] actual, int[] sequence) {
arrays.assertStartsWith(info, failures, actual, sequence);
}
/**
* Verifies that the given array ends with the given sequence of values, without any other values between them.
* Similar to <code>{@link #assertContainsSequence(AssertionInfo, int[], int[])}</code>, but it also verifies that the
* last element in the sequence is also the last element of the given array.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param sequence the sequence of values to look for.
* @throws NullPointerException if the given argument is {@code null}.
* @throws IllegalArgumentException if the given argument is an empty array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array does not end with the given sequence of values.
*/
public void assertEndsWith(AssertionInfo info, int[] actual, int[] sequence) {
arrays.assertEndsWith(info, failures, actual, sequence);
}
/**
* Concrete implementation of {@link ArraySortedAssert#isSorted()}.
*
* @param info contains information about the assertion.
* @param actual the given array.
*/
public void assertIsSorted(AssertionInfo info, int[] actual) {
arrays.assertIsSorted(info, failures, actual);
}
/**
* Concrete implementation of {@link ArraySortedAssert#isSortedAccordingTo(Comparator)}.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param comparator the {@link Comparator} used to compare array elements
*/
public void assertIsSortedAccordingToComparator(AssertionInfo info, int[] actual,
Comparator<? super Integer> comparator) {
Arrays.assertIsSortedAccordingToComparator(info, failures, actual, comparator);
}
public void assertContainsAnyOf(AssertionInfo info, int[] actual, int[] values) {
arrays.assertContainsAnyOf(info, failures, actual, values);
}
}
|
IntArrays
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/Mockito.java
|
{
"start": 126937,
"end": 127974
}
|
class ____ which constructions should be mocked.
* @param mockSettingsFactory a function to create settings to use.
* @param mockInitializer a callback to prepare the methods on a mock after its instantiation.
* @return mock controller
*/
public static <T> MockedConstruction<T> mockConstruction(
Class<T> classToMock,
Function<MockedConstruction.Context, MockSettings> mockSettingsFactory,
MockedConstruction.MockInitializer<T> mockInitializer) {
return MOCKITO_CORE.mockConstruction(classToMock, mockSettingsFactory, mockInitializer);
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param reified don't pass any values to it. It's a trick to detect the class/
|
of
|
java
|
apache__rocketmq
|
broker/src/main/java/org/apache/rocketmq/broker/processor/SendMessageCallback.java
|
{
"start": 982,
"end": 1203
}
|
interface ____ {
/**
* On send complete.
*
* @param ctx send context
* @param response send response
*/
void onComplete(SendMessageContext ctx, RemotingCommand response);
}
|
SendMessageCallback
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/Node.java
|
{
"start": 220,
"end": 1019
}
|
class ____ {
private String name;
private Node parent;
private Set children = new HashSet();
private String description;
public Node() {
}
public Node(String name) {
this.name = name;
}
public Set getChildren() {
return children;
}
public void setChildren(Set children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public Node addChild(Node child) {
children.add( child );
child.setParent( this );
return this;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
Node
|
java
|
grpc__grpc-java
|
testing-proto/src/generated/main/grpc/io/grpc/testing/protobuf/SimpleServiceGrpc.java
|
{
"start": 12449,
"end": 12854
}
|
class ____
implements io.grpc.BindableService, AsyncService {
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return SimpleServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service SimpleService.
* <pre>
* A simple service for test.
* </pre>
*/
public static final
|
SimpleServiceImplBase
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamJob.java
|
{
"start": 26842,
"end": 31044
}
|
class ____ (they might get unpackaged in "." and then
// hide the intended CLASSPATH entry)
// we still package everything else (so that scripts and executable are found in
// Task workdir like distributed Hadoop)
} else {
if (new File(runtimeClasses).isDirectory()) {
packageFiles_.add(runtimeClasses);
} else {
unjarFiles.add(runtimeClasses);
}
}
if (packageFiles_.size() + unjarFiles.size() == 0) {
return null;
}
String tmp = jobConf_.get("stream.tmpdir"); //, "/tmp/${mapreduce.job.user.name}/"
File tmpDir = (tmp == null) ? null : new File(tmp);
// tmpDir=null means OS default tmp dir
File jobJar = File.createTempFile("streamjob", ".jar", tmpDir);
System.out.println("packageJobJar: " + packageFiles_ + " " + unjarFiles + " " + jobJar
+ " tmpDir=" + tmpDir);
if (debug_ == 0) {
jobJar.deleteOnExit();
}
JarBuilder builder = new JarBuilder();
if (verbose_) {
builder.setVerbose(true);
}
String jobJarName = jobJar.getAbsolutePath();
builder.merge(packageFiles_, unjarFiles, jobJarName);
return jobJarName;
}
/**
* get the uris of all the files/caches
*/
protected void getURIs(String lcacheArchives, String lcacheFiles) {
String archives[] = StringUtils.getStrings(lcacheArchives);
String files[] = StringUtils.getStrings(lcacheFiles);
fileURIs = StringUtils.stringToURI(files);
archiveURIs = StringUtils.stringToURI(archives);
}
protected void setJobConf() throws IOException {
if (additionalConfSpec_ != null) {
LOG.warn("-additionalconfspec option is deprecated, please use -conf instead.");
config_.addResource(new Path(additionalConfSpec_));
}
// general MapRed job properties
jobConf_ = new JobConf(config_, StreamJob.class);
// All streaming jobs get the task timeout value
// from the configuration settings.
// The correct FS must be set before this is called!
// (to resolve local vs. dfs drive letter differences)
// (mapreduce.job.working.dir will be lazily initialized ONCE and depends on FS)
for (int i = 0; i < inputSpecs_.size(); i++) {
FileInputFormat.addInputPaths(jobConf_,
(String) inputSpecs_.get(i));
}
String defaultPackage = this.getClass().getPackage().getName();
Class c;
Class fmt = null;
if (inReaderSpec_ == null && inputFormatSpec_ == null) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_ != null) {
if (inputFormatSpec_.equals(TextInputFormat.class.getName())
|| inputFormatSpec_.equals(TextInputFormat.class.getCanonicalName())
|| inputFormatSpec_.equals(TextInputFormat.class.getSimpleName())) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = KeyValueTextInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileInputFormat.class
.getName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class
.getCanonicalName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = SequenceFileInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class.getSimpleName())) {
fmt = SequenceFileAsTextInputFormat.class;
} else {
c = StreamUtil.goodClassOrNull(jobConf_, inputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-inputformat :
|
files
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Combinable.java
|
{
"start": 856,
"end": 968
}
|
class ____ Combinable if its object can be combined with other objects.
* @param <T> The generic type
*/
public
|
is
|
java
|
apache__maven
|
compat/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver.java
|
{
"start": 1262,
"end": 1801
}
|
class ____ implements ConflictResolver {
// ConflictResolver methods -----------------------------------------------
/*
* @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode,
* org.apache.maven.artifact.resolver.ResolutionNode)
*/
@Override
public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) {
return node1.getDepth() <= node2.getDepth() ? node1 : node2;
}
}
|
NearestConflictResolver
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/NegativeCharLiteralTest.java
|
{
"start": 864,
"end": 1190
}
|
class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NegativeCharLiteral.class, getClass());
@Test
public void positive_literalNegativeOne() {
compilationHelper
.addSourceLines(
"Test.java",
"""
|
NegativeCharLiteralTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/azureopenai/embeddings/AzureOpenAiEmbeddingsTaskSettings.java
|
{
"start": 1384,
"end": 4592
}
|
class ____ implements TaskSettings {
public static final String NAME = "azure_openai_embeddings_task_settings";
public static AzureOpenAiEmbeddingsTaskSettings fromMap(Map<String, Object> map) {
ValidationException validationException = new ValidationException();
String user = extractOptionalString(map, USER, ModelConfigurations.TASK_SETTINGS, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new AzureOpenAiEmbeddingsTaskSettings(user);
}
/**
* Creates a new {@link AzureOpenAiEmbeddingsTaskSettings} object by overriding the values in originalSettings with the ones
* passed in via requestSettings if the fields are not null.
* @param originalSettings the original {@link AzureOpenAiEmbeddingsTaskSettings} from the inference entity configuration from storage
* @param requestSettings the {@link AzureOpenAiEmbeddingsTaskSettings} from the request
* @return a new {@link AzureOpenAiEmbeddingsTaskSettings}
*/
public static AzureOpenAiEmbeddingsTaskSettings of(
AzureOpenAiEmbeddingsTaskSettings originalSettings,
AzureOpenAiEmbeddingsRequestTaskSettings requestSettings
) {
var userToUse = requestSettings.user() == null ? originalSettings.user : requestSettings.user();
return new AzureOpenAiEmbeddingsTaskSettings(userToUse);
}
private final String user;
public AzureOpenAiEmbeddingsTaskSettings(@Nullable String user) {
this.user = user;
}
public AzureOpenAiEmbeddingsTaskSettings(StreamInput in) throws IOException {
this.user = in.readOptionalString();
}
@Override
public boolean isEmpty() {
return user == null || user.isEmpty();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (user != null) {
builder.field(USER, user);
}
builder.endObject();
return builder;
}
public String user() {
return user;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_14_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalString(user);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AzureOpenAiEmbeddingsTaskSettings that = (AzureOpenAiEmbeddingsTaskSettings) o;
return Objects.equals(user, that.user);
}
@Override
public int hashCode() {
return Objects.hash(user);
}
@Override
public TaskSettings updatedTaskSettings(Map<String, Object> newSettings) {
AzureOpenAiEmbeddingsRequestTaskSettings requestSettings = AzureOpenAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(newSettings)
);
return of(this, requestSettings);
}
}
|
AzureOpenAiEmbeddingsTaskSettings
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java
|
{
"start": 34818,
"end": 35958
}
|
interface ____ {",
" abstract Builder maybe(int x);",
" abstract Baz build();",
" }",
"}");
Compilation compilation =
javac().withProcessors(new AutoBuilderProcessor()).compile(javaFileObject);
assertThat(compilation).failed();
assertThat(compilation)
.hadErrorContaining(
"[AutoBuilderGetVsSetOrConvert] Parameter type int of setter method should be"
+ " java.util.Optional<java.lang.String> to match parameter \"maybe\" of"
+ " Baz(java.util.Optional<java.lang.String> maybe), or it should be a type that"
+ " can be passed to Optional.of to produce java.util.Optional<java.lang.String>")
.inFile(javaFileObject)
.onLineContaining("maybe(int x)");
}
@Test
public void typeParamMismatch() {
JavaFileObject javaFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoBuilder;",
"import java.util.Optional;",
"",
"
|
Builder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/heuristic/LongBinomialDistribution.java
|
{
"start": 1207,
"end": 7346
}
|
class ____ {
/** 1/2 * log(2π). */
private static final double HALF_LOG_2_PI = 0.5 * FastMath.log(MathUtils.TWO_PI);
/** exact Stirling expansion error for certain values. */
private static final double[] EXACT_STIRLING_ERRORS = {
0.0, /* 0.0 */
0.1534264097200273452913848, /* 0.5 */
0.0810614667953272582196702, /* 1.0 */
0.0548141210519176538961390, /* 1.5 */
0.0413406959554092940938221, /* 2.0 */
0.03316287351993628748511048, /* 2.5 */
0.02767792568499833914878929, /* 3.0 */
0.02374616365629749597132920, /* 3.5 */
0.02079067210376509311152277, /* 4.0 */
0.01848845053267318523077934, /* 4.5 */
0.01664469118982119216319487, /* 5.0 */
0.01513497322191737887351255, /* 5.5 */
0.01387612882307074799874573, /* 6.0 */
0.01281046524292022692424986, /* 6.5 */
0.01189670994589177009505572, /* 7.0 */
0.01110455975820691732662991, /* 7.5 */
0.010411265261972096497478567, /* 8.0 */
0.009799416126158803298389475, /* 8.5 */
0.009255462182712732917728637, /* 9.0 */
0.008768700134139385462952823, /* 9.5 */
0.008330563433362871256469318, /* 10.0 */
0.007934114564314020547248100, /* 10.5 */
0.007573675487951840794972024, /* 11.0 */
0.007244554301320383179543912, /* 11.5 */
0.006942840107209529865664152, /* 12.0 */
0.006665247032707682442354394, /* 12.5 */
0.006408994188004207068439631, /* 13.0 */
0.006171712263039457647532867, /* 13.5 */
0.005951370112758847735624416, /* 14.0 */
0.005746216513010115682023589, /* 14.5 */
0.005554733551962801371038690 /* 15.0 */
};
private final long numberOfTrials;
private final double probabilityOfSuccess;
public LongBinomialDistribution(long numberOfTrials, double probabilityOfSuccess) {
this.numberOfTrials = numberOfTrials;
this.probabilityOfSuccess = probabilityOfSuccess;
}
/**
* For a random variable X whose values are distributed according to this distribution,
* this method returns log(P(X = x)), where log is the natural logarithm.
* In other words, this method represents the logarithm of the probability mass function (PMF) for the distribution.
* Note that due to the floating point precision and under/overflow issues,
* this method will for some distributions be more precise and faster than computing the logarithm of probability(int).
*/
public double logProbability(long x) {
if (numberOfTrials == 0) {
return (x == 0) ? 0. : Double.NEGATIVE_INFINITY;
}
double ret;
if (x < 0 || x > numberOfTrials) {
ret = Double.NEGATIVE_INFINITY;
} else {
ret = logBinomialProbability(x, numberOfTrials, probabilityOfSuccess, 1.0 - probabilityOfSuccess);
}
return ret;
}
/**
* A part of the deviance portion of the saddle point approximation.
* References:
* Catherine Loader (2000). "Fast and Accurate Computation of Binomial Probabilities.". http://www.herine.net/stat/papers/dbinom.pdf
* @param x – the x value.
* @param mu – the average.
* @return : a part of the deviance.
*/
static double getDeviancePart(double x, double mu) {
double ret;
if (FastMath.abs(x - mu) < 0.1 * (x + mu)) {
double d = x - mu;
double v = d / (x + mu);
double s1 = v * d;
double s = Double.NaN;
double ej = 2.0 * x * v;
v *= v;
int j = 1;
while (s1 != s) {
s = s1;
ej *= v;
s1 = s + ej / ((j * 2) + 1);
++j;
}
ret = s1;
} else {
ret = x * FastMath.log(x / mu) + mu - x;
}
return ret;
}
/**
* Compute the error of Stirling's series at the given value.
* References:
* Eric W. Weisstein. "Stirling's Series." From MathWorld--A Wolfram Web
* Resource. http://mathworld.wolfram.com/StirlingsSeries.html
*
* @param z the value.
* @return the Striling's series error.
*/
static double getStirlingError(double z) {
double ret;
if (z < 15.0) {
double z2 = 2.0 * z;
if (FastMath.floor(z2) == z2) {
ret = EXACT_STIRLING_ERRORS[(int) z2];
} else {
ret = Gamma.logGamma(z + 1.0) - (z + 0.5) * FastMath.log(z) + z - HALF_LOG_2_PI;
}
} else {
double z2 = z * z;
ret = (0.083333333333333333333 - (0.00277777777777777777778 - (0.00079365079365079365079365 - (0.000595238095238095238095238
- 0.0008417508417508417508417508 / z2) / z2) / z2) / z2) / z;
}
return ret;
}
/**
* Compute the logarithm of the PMF for a binomial distribution using the saddle point expansion.
* Params:
* @param x – the value at which the probability is evaluated.
* @param n – the number of trials.
* @param p – the probability of success.
* @param q – the probability of failure (1 - p).
* @return : log(p(x)).
*/
static double logBinomialProbability(long x, long n, double p, double q) {
double ret;
if (x == 0) {
if (p < 0.1) {
ret = -getDeviancePart(n, n * q) - n * p;
} else {
ret = n * FastMath.log(q);
}
} else if (x == n) {
if (q < 0.1) {
ret = -getDeviancePart(n, n * p) - n * q;
} else {
ret = n * FastMath.log(p);
}
} else {
ret = getStirlingError(n) - getStirlingError(x) - getStirlingError(n - x) - getDeviancePart(x, n * p) - getDeviancePart(
n - x,
n * q
);
double f = (MathUtils.TWO_PI * x * (n - x)) / n;
ret = -0.5 * FastMath.log(f) + ret;
}
return ret;
}
}
|
LongBinomialDistribution
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.