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 | apache__flink | flink-core/src/test/java/org/apache/flink/testutils/TestingUtils.java | {
"start": 1481,
"end": 2287
} | class ____ {
private static final UUID ZERO_UUID = new UUID(0L, 0L);
public static final Duration TESTING_DURATION = Duration.ofMinutes(2L);
public static final Duration TIMEOUT = Duration.ofMinutes(1L);
public static final Duration DEFAULT_ASK_TIMEOUT = Duration.ofSeconds(200);
public static Duration infiniteTime() {
return Duration.ofMillis(Integer.MAX_VALUE);
}
public static Duration infiniteDuration() {
// we cannot use Long.MAX_VALUE because the Duration stores it in nanosecond resolution and
// calculations will easily cause overflows --> 1 year should be long enough for "infinity"
return Duration.ofDays(365L);
}
// To make debugging logs easier, we use a custom thread factory that names the thread.
static | TestingUtils |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/support/PurchaseOrder.java | {
"start": 926,
"end": 1992
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
private final String product;
private final double amount;
public PurchaseOrder(String product, double amount) {
this.product = product;
this.amount = amount;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (this.getClass() != other.getClass()) {
return false;
}
PurchaseOrder that = (PurchaseOrder) other;
return this.product.equals(that.product) && this.amount == that.amount;
}
@Override
public int hashCode() {
return product.hashCode() * 37 + (int) Math.round(amount);
}
@Override
public String toString() {
return "PurchaseOrder[" + product + " x " + amount + "]";
}
public double getAmount() {
return amount;
}
public String getProduct() {
return product;
}
}
| PurchaseOrder |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/signatures/PublisherSignatureTest.java | {
"start": 4558,
"end": 4975
} | class ____ extends Spy {
@Outgoing("C")
public PublisherBuilder<Message<Integer>> produce() {
return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
.map(Message::of);
}
@Incoming("C")
public void consume(Integer item) {
items.add(item);
}
}
@ApplicationScoped
public static | BeanProducingAPublisherBuilderOfMessage |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest.java | {
"start": 2271,
"end": 2474
} | class ____ extends A {
public int age;
public C() {
}
public C(int id, int age) {
this.id = id;
this.age = age;
}
}
public static | C |
java | apache__camel | components/camel-oauth/src/main/java/org/apache/camel/oauth/InMemorySessionStore.java | {
"start": 1259,
"end": 3935
} | class ____ implements OAuthSessionStore {
protected final Logger log = LoggerFactory.getLogger(getClass());
private final Map<String, OAuthSession> sessions = new HashMap<>();
@Override
public Optional<OAuthSession> getSession(Exchange exchange) {
var msg = exchange.getMessage();
// First, try the CamelOAuthSessionId header
var sessionId = msg.getHeader(CAMEL_OAUTH_SESSION_ID, String.class);
// Fallback to our session cookie
if (sessionId == null) {
var cookies = getCookies(exchange);
if (cookies.get(CAMEL_OAUTH_COOKIE) == null) {
log.warn("No '{}' Cookie in HTTP request", CAMEL_OAUTH_COOKIE);
return Optional.empty();
}
sessionId = cookies.get(CAMEL_OAUTH_COOKIE);
}
var maybeSession = Optional.ofNullable(sessions.get(sessionId));
if (maybeSession.isEmpty()) {
log.warn("No OAuthSession for: {}", sessionId);
}
return maybeSession;
}
public OAuthSession createSession(Exchange exchange) {
var sessionId = UUID.randomUUID().toString();
var session = new InMemorySession(sessionId);
sessions.put(sessionId, session);
var msg = exchange.getMessage();
log.info("New OAuthSession: {}", sessionId);
setSessionCookie(msg, session);
msg.setHeader(OAuth.CAMEL_OAUTH_SESSION_ID, sessionId);
return session;
}
private Map<String, String> getCookies(Exchange exchange) {
var msg = exchange.getMessage();
var maybeCookie = Optional.ofNullable(msg.getHeader("Cookie"));
if (maybeCookie.isEmpty()) {
log.warn("No Cookie in HTTP request");
return Map.of();
}
var value = maybeCookie.get().toString();
var cookieMap = Arrays.stream(value.split(";"))
.map(String::trim)
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(
arr -> arr[0],
arr -> arr.length > 1 ? arr[1] : ""));
return cookieMap;
}
private void setSessionCookie(Message msg, OAuthSession session) {
var sessionId = session.getSessionId();
var cookieId = "%s=%s".formatted(CAMEL_OAUTH_COOKIE, sessionId);
if (msg.getHeader("Set-Cookie") != null) {
throw new IllegalStateException("Duplicate 'Set-Cookie' header");
}
var cookie = cookieId + "; Path=/; HttpOnly; SameSite=None; Secure";
msg.setHeader("Set-Cookie", cookie);
log.debug("Set-Cookie: {}", cookie);
}
}
| InMemorySessionStore |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternDynamicFormatter.java | {
"start": 17344,
"end": 18282
} | class ____ implements InstantPatternFormatter {
private final String pattern;
private final Locale locale;
private final TimeZone timeZone;
private final ChronoUnit precision;
AbstractFormatter(
final String pattern, final Locale locale, final TimeZone timeZone, final ChronoUnit precision) {
this.pattern = pattern;
this.locale = locale;
this.timeZone = timeZone;
this.precision = precision;
}
@Override
public ChronoUnit getPrecision() {
return precision;
}
@Override
public String getPattern() {
return pattern;
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public TimeZone getTimeZone() {
return timeZone;
}
}
abstract static | AbstractFormatter |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestReporter.java | {
"start": 1655,
"end": 2405
} | class ____ {
private static final Path rootTempDir =
new Path(System.getProperty("test.build.data", "/tmp"));
private static final Path testRootTempDir =
new Path(rootTempDir, "TestReporter");
private static FileSystem fs = null;
@BeforeAll
public static void setup() throws Exception {
fs = FileSystem.getLocal(new Configuration());
fs.delete(testRootTempDir, true);
fs.mkdirs(testRootTempDir);
}
@AfterAll
public static void cleanup() throws Exception {
fs.delete(testRootTempDir, true);
}
// an input with 4 lines
private static final String INPUT = "Hi\nHi\nHi\nHi\n";
private static final int INPUT_LINES = INPUT.split("\n").length;
@SuppressWarnings("deprecation")
static | TestReporter |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/util/NativeImageUtils.java | {
"start": 1318,
"end": 1873
} | class ____ will be contained in the image). If
* the property returns the string given by {@link #PROPERTY_IMAGE_CODE_VALUE_RUNTIME} the code
* is executing at image runtime. Otherwise, the property is not set.
*/
public static final String PROPERTY_IMAGE_CODE_KEY = "org.graalvm.nativeimage.imagecode";
/**
* Holds the string that will be returned by the system property for
* {@link NativeImageUtils#PROPERTY_IMAGE_CODE_KEY} if code is executing in the context of image
* building (e.g. in a static initializer of | that |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RSortedSet.java | {
"start": 816,
"end": 7062
} | interface ____<V> extends SortedSet<V>, RExpirable {
/**
* Returns <code>RMapReduce</code> object associated with this object
*
* @param <KOut> output key
* @param <VOut> output value
* @return MapReduce instance
*/
<KOut, VOut> RCollectionMapReduce<V, KOut, VOut> mapReduce();
Collection<V> readAll();
RFuture<Collection<V>> readAllAsync();
/**
* Removes and returns the head element or {@code null} if this sorted set is empty.
*
* @return the head element,
* or {@code null} if this sorted set is empty
*/
V pollFirst();
/**
* Removes and returns the head elements of this sorted set.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param count - elements amount
* @return the head elements of this sorted set
*/
Collection<V> pollFirst(int count);
/**
* Removes and returns the head element or {@code null} if this sorted set is empty.
*
* @param duration how long to wait before giving up
* @return the head element,
* or {@code null} if this sorted set is empty
*/
V pollFirst(Duration duration);
/**
* Removes and returns the head elements.
* <p>
* Requires <b>Redis 7.0.0 and higher.</b>
*
* @param duration how long to wait before giving up
* @param count elements amount
* @return the head elements
*/
List<V> pollFirst(Duration duration, int count);
/**
* Removes and returns the head element or {@code null} if this sorted set is empty.
*
* @return the head element,
* or {@code null} if this sorted set is empty
*/
RFuture<V> pollFirstAsync();
/**
* Removes and returns the head elements of this sorted set.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param count - elements amount
* @return the head elements of this sorted set
*/
RFuture<Collection<V>> pollFirstAsync(int count);
/**
* Removes and returns the head element or {@code null} if this sorted set is empty.
*
* @param duration how long to wait before giving up
* @return the head element,
* or {@code null} if this sorted set is empty
*/
RFuture<V> pollFirstAsync(Duration duration);
/**
* Removes and returns the head elements.
* <p>
* Requires <b>Redis 7.0.0 and higher.</b>
*
* @param duration how long to wait before giving up
* @param count elements amount
* @return the head elements
*/
RFuture<List<V>> pollFirstAsync(Duration duration, int count);
/**
* Removes and returns the tail element or {@code null} if this sorted set is empty.
*
* @return the tail element or {@code null} if this sorted set is empty
*/
V pollLast();
/**
* Removes and returns the tail elements of this sorted set.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param count - elements amount
* @return the tail elements of this sorted set
*/
Collection<V> pollLast(int count);
/**
* Removes and returns the tail element or {@code null} if this sorted set is empty.
*
* @param duration how long to wait before giving up
* @return the tail element,
* or {@code null} if this sorted set is empty
*/
V pollLast(Duration duration);
/**
* Removes and returns the tail elements.
* <p>
* Requires <b>Redis 7.0.0 and higher.</b>
*
* @param duration how long to wait before giving up
* @param count elements amount
* @return the tail elements
*/
List<V> pollLast(Duration duration, int count);
/**
* Removes and returns the tail element or {@code null} if this sorted set is empty.
*
* @return the tail element or {@code null} if this sorted set is empty
*/
RFuture<V> pollLastAsync();
/**
* Removes and returns the tail elements of this sorted set.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param count - elements amount
* @return the tail elements of this sorted set
*/
RFuture<Collection<V>> pollLastAsync(int count);
/**
* Removes and returns the tail element or {@code null} if this sorted set is empty.
*
* @param duration how long to wait before giving up
* @return the tail element,
* or {@code null} if this sorted set is empty
*/
RFuture<V> pollLastAsync(Duration duration);
/**
* Removes and returns the tail elements.
* <p>
* Requires <b>Redis 7.0.0 and higher.</b>
*
* @param duration how long to wait before giving up
* @param count elements amount
* @return the tail elements
*/
RFuture<List<V>> pollLastAsync(Duration duration, int count);
RFuture<Boolean> addAsync(V value);
RFuture<Boolean> removeAsync(Object value);
/**
* Sets new comparator only if current set is empty
*
* @param comparator for values
* @return <code>true</code> if new comparator setted
* <code>false</code> otherwise
*/
boolean trySetComparator(Comparator<? super V> comparator);
/**
* Returns element iterator that can be shared across multiple applications.
* Creating multiple iterators on the same object with this method will result in a single shared iterator.
* See {@linkplain RList#distributedIterator(String, int)} for creating different iterators.
* @param count batch size
* @return shared elements iterator
*/
Iterator<V> distributedIterator(int count);
/**
* Returns iterator over elements that match specified pattern. Iterator can be shared across multiple applications.
* Creating multiple iterators on the same object with this method will result in a single shared iterator.
* Iterator name must be resolved to the same hash slot as list name.
* @param count batch size
* @param iteratorName redis object name to which cursor will be saved
* @return shared elements iterator
*/
Iterator<V> distributedIterator(String iteratorName, int count);
}
| RSortedSet |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/datatiers/NodesDataTiersUsageTransportAction.java | {
"start": 2232,
"end": 7179
} | class ____ extends TransportNodesAction<
NodesDataTiersUsageTransportAction.NodesRequest,
NodesDataTiersUsageTransportAction.NodesResponse,
NodesDataTiersUsageTransportAction.NodeRequest,
NodeDataTiersUsage,
Void> {
public static final ActionType<NodesResponse> TYPE = new ActionType<>("cluster:monitor/nodes/data_tier_usage");
private static final CommonStatsFlags STATS_FLAGS = new CommonStatsFlags().clear()
.set(CommonStatsFlags.Flag.Docs, true)
.set(CommonStatsFlags.Flag.Store, true);
private final IndicesService indicesService;
@Inject
public NodesDataTiersUsageTransportAction(
ThreadPool threadPool,
ClusterService clusterService,
TransportService transportService,
IndicesService indicesService,
ActionFilters actionFilters
) {
super(
TYPE.name(),
clusterService,
transportService,
actionFilters,
NodeRequest::new,
threadPool.executor(ThreadPool.Names.MANAGEMENT)
);
this.indicesService = indicesService;
}
@Override
protected NodesResponse newResponse(NodesRequest request, List<NodeDataTiersUsage> responses, List<FailedNodeException> failures) {
return new NodesResponse(clusterService.getClusterName(), responses, failures);
}
@Override
protected NodeRequest newNodeRequest(NodesRequest request) {
return new NodeRequest();
}
@Override
protected NodeDataTiersUsage newNodeResponse(StreamInput in, DiscoveryNode node) throws IOException {
return new NodeDataTiersUsage(in);
}
@Override
protected NodeDataTiersUsage nodeOperation(NodeRequest nodeRequest, Task task) {
assert task instanceof CancellableTask;
DiscoveryNode localNode = clusterService.localNode();
NodeIndicesStats nodeIndicesStats = indicesService.stats(STATS_FLAGS, true);
ClusterState state = clusterService.state();
RoutingNode routingNode = state.getRoutingNodes().node(localNode.getId());
Map<String, NodeDataTiersUsage.UsageStats> usageStatsByTier = aggregateStats(routingNode, state.metadata(), nodeIndicesStats);
return new NodeDataTiersUsage(clusterService.localNode(), usageStatsByTier);
}
// For bwc & testing purposes
static Map<String, NodeDataTiersUsage.UsageStats> aggregateStats(
RoutingNode routingNode,
Metadata metadata,
NodeIndicesStats nodeIndicesStats
) {
if (routingNode == null) {
return Map.of();
}
Map<String, NodeDataTiersUsage.UsageStats> usageStatsByTier = new HashMap<>();
Set<String> localIndices = StreamSupport.stream(routingNode.spliterator(), false)
.map(routing -> routing.index().getName())
.collect(Collectors.toSet());
for (String indexName : localIndices) {
IndexMetadata indexMetadata = metadata.getProject().index(indexName);
if (indexMetadata == null) {
continue;
}
String tier = indexMetadata.getTierPreference().isEmpty() ? null : indexMetadata.getTierPreference().get(0);
if (tier != null) {
NodeDataTiersUsage.UsageStats usageStats = usageStatsByTier.computeIfAbsent(
tier,
ignored -> new NodeDataTiersUsage.UsageStats()
);
List<IndexShardStats> allShardStats = nodeIndicesStats.getShardStats(indexMetadata.getIndex());
if (allShardStats != null) {
for (IndexShardStats indexShardStats : allShardStats) {
final StoreStats storeStats = indexShardStats.getTotal().getStore();
usageStats.incrementTotalSize(storeStats == null ? 0L : storeStats.totalDataSetSizeInBytes());
final DocsStats docsStats = indexShardStats.getTotal().getDocs();
usageStats.incrementDocCount(docsStats == null ? 0L : docsStats.getCount());
ShardRouting shardRouting = routingNode.getByShardId(indexShardStats.getShardId());
if (shardRouting != null && shardRouting.state() == ShardRoutingState.STARTED) {
usageStats.incrementTotalShardCount(1);
// Accumulate stats about started primary shards
StoreStats primaryStoreStats = indexShardStats.getPrimary().getStore();
if (shardRouting.primary() && primaryStoreStats != null) {
usageStats.addPrimaryShardSize(primaryStoreStats.totalDataSetSizeInBytes());
}
}
}
}
}
}
return usageStatsByTier;
}
public static | NodesDataTiersUsageTransportAction |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/BootstrapTestUtilsMergedConfigTests.java | {
"start": 22466,
"end": 22552
} | class ____ extends EmptyConfigTestCase {
@Configuration
static | SubEmptyConfigTestCase |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableModifyClusteredBy.java | {
"start": 864,
"end": 1406
} | class ____ extends SQLObjectImpl implements SQLAlterTableItem {
private List<SQLName> clusterColumns = new ArrayList<SQLName>();
public List<SQLName> getClusterColumns() {
return clusterColumns;
}
public void addClusterColumn(SQLName name) {
this.clusterColumns.add(name);
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, clusterColumns);
}
visitor.endVisit(this);
}
}
| SQLAlterTableModifyClusteredBy |
java | apache__camel | components/camel-ai/camel-djl/src/main/java/org/apache/camel/component/djl/ImageNetUtil.java | {
"start": 1223,
"end": 1304
} | class ____ handling ImageNet (https://image-net.org/) classifications.
*/
public | for |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfAssignmentTest.java | {
"start": 9622,
"end": 9733
} | class ____ {
Foo foo;
Bar bar;
}
private static | Foobar |
java | quarkusio__quarkus | extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/GraphQLBlockingModeTest.java | {
"start": 12923,
"end": 14357
} | class ____ {
private long id;
private String name;
private int priority;
private String state;
private String group;
public TestThread() {
super();
}
public TestThread(long id, String name, int priority, String state, String group) {
this.id = id;
this.name = name;
this.priority = priority;
this.state = state;
this.group = group;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVertxContextClassName() {
Context vc = Vertx.currentContext();
return vc.getClass().getName();
}
}
}
| TestThread |
java | apache__maven | its/core-it-support/core-it-plugins/maven-it-plugin-project/src/main/java/org/apache/maven/plugin/coreit/BuildRemotePomMojo.java | {
"start": 1579,
"end": 3802
} | class ____ extends AbstractPomMojo {
/**
* The properties file to dump the POM info to.
*/
@Parameter(defaultValue = "target/pom.properties")
private File propertiesFile;
/**
* The local repository.
*/
@Parameter(defaultValue = "${localRepository}", readonly = true, required = true)
private ArtifactRepository localRepository;
/**
* The remote repositories of the current Maven project.
*/
@Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true)
private List<ArtifactRepository> remoteRepositories;
/**
* The artifact factory.
*
*/
@Component
private ArtifactFactory factory;
/**
* The dependencies to resolve.
*
*/
@Parameter
private Dependency[] dependencies;
/**
* Runs this mojo.
*
* @throws MojoExecutionException If the artifact file has not been set.
*/
public void execute() throws MojoExecutionException {
Properties props = new Properties();
getLog().info("[MAVEN-CORE-IT-LOG] Building remote POMs");
if (dependencies != null) {
for (Dependency dependency : dependencies) {
Artifact artifact = factory.createArtifactWithClassifier(
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersion(),
dependency.getType(),
dependency.getClassifier());
String id = artifact.getId();
getLog().info("[MAVEN-CORE-IT-LOG] Building " + id);
try {
MavenProject project = builder.buildFromRepository(artifact, remoteRepositories, localRepository);
dump(props, id + ".", project);
} catch (Exception e) {
getLog().warn("Failed to build remote POM for " + artifact.getId(), e);
}
put(props, id + ".file", artifact.getFile());
put(props, id + ".version", artifact.getVersion());
}
}
store(props, propertiesFile);
}
}
| BuildRemotePomMojo |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/analysis/Analysis.java | {
"start": 3496,
"end": 17761
} | class ____ {
private static final Logger logger = LogManager.getLogger(Analysis.class);
public static CharArraySet parseStemExclusion(Settings settings, CharArraySet defaultStemExclusion) {
String value = settings.get("stem_exclusion");
if ("_none_".equals(value)) {
return CharArraySet.EMPTY_SET;
}
List<String> stemExclusion = settings.getAsList("stem_exclusion", null);
if (stemExclusion != null) {
// LUCENE 4 UPGRADE: Should be settings.getAsBoolean("stem_exclusion_case", false)?
return new CharArraySet(stemExclusion, false);
} else {
return defaultStemExclusion;
}
}
private static final Map<String, Set<?>> NAMED_STOP_WORDS = Map.ofEntries(
entry("_arabic_", ArabicAnalyzer.getDefaultStopSet()),
entry("_armenian_", ArmenianAnalyzer.getDefaultStopSet()),
entry("_basque_", BasqueAnalyzer.getDefaultStopSet()),
entry("_bengali_", BengaliAnalyzer.getDefaultStopSet()),
entry("_brazilian_", BrazilianAnalyzer.getDefaultStopSet()),
entry("_bulgarian_", BulgarianAnalyzer.getDefaultStopSet()),
entry("_catalan_", CatalanAnalyzer.getDefaultStopSet()),
entry("_czech_", CzechAnalyzer.getDefaultStopSet()),
entry("_danish_", DanishAnalyzer.getDefaultStopSet()),
entry("_dutch_", DutchAnalyzer.getDefaultStopSet()),
entry("_english_", EnglishAnalyzer.getDefaultStopSet()),
entry("_estonian_", EstonianAnalyzer.getDefaultStopSet()),
entry("_finnish_", FinnishAnalyzer.getDefaultStopSet()),
entry("_french_", FrenchAnalyzer.getDefaultStopSet()),
entry("_galician_", GalicianAnalyzer.getDefaultStopSet()),
entry("_german_", GermanAnalyzer.getDefaultStopSet()),
entry("_greek_", GreekAnalyzer.getDefaultStopSet()),
entry("_hindi_", HindiAnalyzer.getDefaultStopSet()),
entry("_hungarian_", HungarianAnalyzer.getDefaultStopSet()),
entry("_indonesian_", IndonesianAnalyzer.getDefaultStopSet()),
entry("_irish_", IrishAnalyzer.getDefaultStopSet()),
entry("_italian_", ItalianAnalyzer.getDefaultStopSet()),
entry("_latvian_", LatvianAnalyzer.getDefaultStopSet()),
entry("_lithuanian_", LithuanianAnalyzer.getDefaultStopSet()),
entry("_norwegian_", NorwegianAnalyzer.getDefaultStopSet()),
entry("_persian_", PersianAnalyzer.getDefaultStopSet()),
entry("_portuguese_", PortugueseAnalyzer.getDefaultStopSet()),
entry("_romanian_", RomanianAnalyzer.getDefaultStopSet()),
entry("_russian_", RussianAnalyzer.getDefaultStopSet()),
entry("_serbian_", SerbianAnalyzer.getDefaultStopSet()),
entry("_sorani_", SoraniAnalyzer.getDefaultStopSet()),
entry("_spanish_", SpanishAnalyzer.getDefaultStopSet()),
entry("_swedish_", SwedishAnalyzer.getDefaultStopSet()),
entry("_thai_", ThaiAnalyzer.getDefaultStopSet()),
entry("_turkish_", TurkishAnalyzer.getDefaultStopSet())
);
public static CharArraySet parseWords(
Environment env,
Settings settings,
String name,
CharArraySet defaultWords,
Map<String, Set<?>> namedWords,
boolean ignoreCase
) {
String value = settings.get(name);
if (value != null) {
if ("_none_".equals(value)) {
return CharArraySet.EMPTY_SET;
} else {
return resolveNamedWords(settings.getAsList(name), namedWords, ignoreCase);
}
}
List<String> pathLoadedWords = getWordList(env, settings, name);
if (pathLoadedWords != null) {
return resolveNamedWords(pathLoadedWords, namedWords, ignoreCase);
}
return defaultWords;
}
public static CharArraySet parseCommonWords(Environment env, Settings settings, CharArraySet defaultCommonWords, boolean ignoreCase) {
return parseWords(env, settings, "common_words", defaultCommonWords, NAMED_STOP_WORDS, ignoreCase);
}
public static CharArraySet parseArticles(Environment env, Settings settings) {
boolean articlesCase = settings.getAsBoolean("articles_case", false);
return parseWords(env, settings, "articles", null, null, articlesCase);
}
public static CharArraySet parseStopWords(Environment env, Settings settings, CharArraySet defaultStopWords) {
boolean stopwordsCase = settings.getAsBoolean("stopwords_case", false);
return parseStopWords(env, settings, defaultStopWords, stopwordsCase);
}
public static CharArraySet parseStopWords(Environment env, Settings settings, CharArraySet defaultStopWords, boolean ignoreCase) {
return parseWords(env, settings, "stopwords", defaultStopWords, NAMED_STOP_WORDS, ignoreCase);
}
private static CharArraySet resolveNamedWords(Collection<String> words, Map<String, Set<?>> namedWords, boolean ignoreCase) {
if (namedWords == null) {
return new CharArraySet(words, ignoreCase);
}
CharArraySet setWords = new CharArraySet(words.size(), ignoreCase);
for (String word : words) {
if (namedWords.containsKey(word)) {
setWords.addAll(namedWords.get(word));
} else {
setWords.add(word);
}
}
return setWords;
}
public static CharArraySet getWordSet(Environment env, Settings settings, String settingsPrefix) {
List<String> wordList = getWordList(env, settings, settingsPrefix);
if (wordList == null) {
return null;
}
boolean ignoreCase = settings.getAsBoolean(settingsPrefix + "_case", false);
return new CharArraySet(wordList, ignoreCase);
}
/**
* Fetches a list of words from the specified settings file. The list should either be available at the key
* specified by settingsPrefix or in a file specified by settingsPrefix + _path.
*
* @throws IllegalArgumentException
* If the word list cannot be found at either key.
*/
public static List<String> getWordList(Environment env, Settings settings, String settingPrefix) {
return getWordList(env, settings, settingPrefix + "_path", settingPrefix, true);
}
/**
* Fetches a list of words from the specified settings file. The list should either be available at the key
* specified by <code>settingList</code> or in a file specified by <code>settingPath</code>.
*
* @throws IllegalArgumentException
* If the word list cannot be found at either key.
*/
public static List<String> getWordList(
Environment env,
Settings settings,
String settingPath,
String settingList,
boolean removeComments
) {
String wordListPath = settings.get(settingPath, null);
if (wordListPath == null) {
List<String> explicitWordList = settings.getAsList(settingList, null);
if (explicitWordList == null) {
return null;
} else {
return explicitWordList;
}
}
final Path path = env.configDir().resolve(wordListPath);
try {
return loadWordList(path, removeComments);
} catch (CharacterCodingException ex) {
String message = Strings.format(
"Unsupported character encoding detected while reading %s: %s - files must be UTF-8 encoded",
settingPath,
path
);
throw new IllegalArgumentException(message, ex);
} catch (IOException ioe) {
String message = Strings.format("IOException while reading %s: %s", settingPath, path);
throw new IllegalArgumentException(message, ioe);
} catch (SecurityException ace) {
throw new IllegalArgumentException(Strings.format("Access denied trying to read file %s: %s", settingPath, path), ace);
}
}
public static List<String> getWordList(
Environment env,
Settings settings,
String settingPath,
String settingList,
String settingLenient,
boolean removeComments,
boolean checkDuplicate
) {
boolean deduplicateDictionary = settings.getAsBoolean(settingLenient, false);
final List<String> ruleList = getWordList(env, settings, settingPath, settingList, removeComments);
if (ruleList != null && ruleList.isEmpty() == false && checkDuplicate) {
return deDuplicateRules(ruleList, deduplicateDictionary == false);
}
return ruleList;
}
/**
* This method checks for any duplicate rules in the provided ruleList. Each rule in the list is parsed with CSVUtil.parse
* to separate the rule into individual components, represented as a String array. Only the first component from each rule
* is considered in the duplication check.
*
* The method will ignore any line that starts with a '#' character, treating it as a comment.
*
* The check is performed by adding the first component of each rule into a HashSet (dup), which does not allow duplicates.
* If the addition to the HashSet returns false, it means that item was already present in the set, indicating a duplicate.
* In such a case, an IllegalArgumentException is thrown specifying the duplicate term and the line number in the original list.
*
* Optionally the function will return the deduplicated list
*
* @param ruleList The list of rules to check for duplicates.
* @throws IllegalArgumentException If a duplicate rule is found.
*/
private static List<String> deDuplicateRules(List<String> ruleList, boolean failOnDuplicate) {
Set<String> duplicateKeys = new HashSet<>();
List<String> deduplicatedList = new ArrayList<>();
for (int lineNum = 0; lineNum < ruleList.size(); lineNum++) {
String line = ruleList.get(lineNum);
// ignore lines beginning with # as those are comments
if (line.startsWith("#") == false) {
String[] values = CSVUtil.parse(line);
if (duplicateKeys.add(values[0]) == false) {
if (failOnDuplicate) {
throw new IllegalArgumentException(
"Found duplicate term [" + values[0] + "] in user dictionary " + "at line [" + (lineNum + 1) + "]"
);
} else {
logger.warn("Ignoring duplicate term [" + values[0] + "] in user dictionary " + "at line [" + (lineNum + 1) + "]");
}
} else {
deduplicatedList.add(line);
}
} else {
deduplicatedList.add(line);
}
}
return Collections.unmodifiableList(deduplicatedList);
}
private static List<String> loadWordList(Path path, boolean removeComments) throws IOException {
final List<String> result = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String word;
while ((word = br.readLine()) != null) {
if (Strings.hasText(word) == false) {
continue;
}
if (removeComments == false || word.startsWith("#") == false) {
result.add(word.trim());
}
}
}
return result;
}
/**
* @return null If no settings set for "settingsPrefix" then return <code>null</code>.
* @throws IllegalArgumentException
* If the Reader can not be instantiated.
*/
public static Reader getReaderFromFile(Environment env, String filePath, String settingPrefix) {
if (filePath == null) {
return null;
}
final Path path = env.configDir().resolve(filePath);
try {
return Files.newBufferedReader(path, StandardCharsets.UTF_8);
} catch (CharacterCodingException ex) {
String message = String.format(
Locale.ROOT,
"Unsupported character encoding detected while reading %s_path: %s files must be UTF-8 encoded",
settingPrefix,
path.toString()
);
throw new IllegalArgumentException(message, ex);
} catch (IOException ioe) {
String message = String.format(Locale.ROOT, "IOException while reading %s_path: %s", settingPrefix, path.toString());
throw new IllegalArgumentException(message, ioe);
}
}
public static Reader getReaderFromIndex(
String synonymsSet,
SynonymsManagementAPIService synonymsManagementAPIService,
boolean ignoreMissing
) {
final PlainActionFuture<PagedResult<SynonymRule>> synonymsLoadingFuture = new PlainActionFuture<>();
synonymsManagementAPIService.getSynonymSetRules(synonymsSet, synonymsLoadingFuture);
PagedResult<SynonymRule> results;
try {
results = synonymsLoadingFuture.actionGet();
} catch (Exception e) {
if (ignoreMissing == false) {
throw e;
}
boolean notFound = e instanceof ResourceNotFoundException;
String message = String.format(
Locale.ROOT,
"Synonyms set %s %s. Synonyms will not be applied to search results on indices that use this synonym set",
synonymsSet,
notFound ? "not found" : "could not be loaded"
);
if (notFound) {
logger.warn(message);
} else {
logger.error(message, e);
}
results = new PagedResult<>(0, new SynonymRule[0]);
}
SynonymRule[] synonymRules = results.pageResults();
StringBuilder sb = new StringBuilder();
for (SynonymRule synonymRule : synonymRules) {
sb.append(synonymRule.synonyms()).append(System.lineSeparator());
}
return new StringReader(sb.toString());
}
}
| Analysis |
java | google__dagger | javatests/dagger/internal/codegen/ComponentProcessorTest.java | {
"start": 34961,
"end": 35774
} | interface ____ {",
" A a();",
" other.test.A otherA();",
"}");
CompilerTests.daggerCompiler(aFile, otherAFile, moduleFile, otherModuleFile, componentFile)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(0);
subject.generatedSource(goldenFileRule.goldenSource("test/DaggerTestComponent"));
});
}
@Test
public void ignoresDependencyMethodsFromObject() throws Exception {
Source injectedTypeFile =
CompilerTests.javaSource(
"test.InjectedType",
"package test;",
"",
"import javax.inject.Inject;",
"import javax.inject.Provider;",
"",
"final | TestComponent |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdManyToOneFetchTest.java | {
"start": 3544,
"end": 3825
} | class ____ {
@ManyToOne( fetch = FetchType.LAZY )
private EntityC entityC;
private String name;
public EntityBId() {
}
public EntityBId(EntityC entityC, String name) {
this.entityC = entityC;
this.name = name;
}
}
@Entity( name = "EntityC" )
static | EntityBId |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java | {
"start": 13192,
"end": 13253
} | class ____ {
String s1;
static | Outer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/AutoValueBuilderDefaultsInConstructorTest.java | {
"start": 2195,
"end": 2410
} | class ____ {
abstract int foo();
Builder builder() {
return new AutoValue_Test.Builder();
}
@AutoValue.Builder
abstract static | Test |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AccessGrantConfiguration.java | {
"start": 1442,
"end": 4540
} | class ____ extends AbstractHadoopTestBase {
/**
* This credential provider will be attached to any client
* that has been configured with the S3 Access Grants plugin.
* {@code software.amazon.awssdk.s3accessgrants.plugin.S3AccessGrantsPlugin}.
*/
public static final String S3_ACCESS_GRANTS_EXPECTED_CREDENTIAL_PROVIDER_CLASS =
S3AccessGrantsIdentityProvider.class.getName();
@Test
public void testS3AccessGrantsEnabled() throws IOException, URISyntaxException {
assertCredentialProviderClass(
createConfig(true),
true,
"S3 Access Grants is explicitly enabled on an S3 Async Client",
true);
assertCredentialProviderClass(
createConfig(true),
false,
"S3 Access Grants is explicitly enabled on an S3 Non-Async Client",
true);
}
@Test
public void testS3AccessGrantsDisabled() throws IOException, URISyntaxException {
assertCredentialProviderClass(
new Configuration(),
true,
"S3 Access Grants is implicitly disabled (default behavior) on an S3 Async Client",
false);
assertCredentialProviderClass(
new Configuration(),
false,
"S3 Access Grants is implicitly disabled (default behavior) on an S3 Non-Async Client",
false);
assertCredentialProviderClass(
createConfig(false),
true,
"S3 Access Grants is explicitly disabled on an S3 Async Client",
false);
assertCredentialProviderClass(
createConfig(false),
false,
"S3 Access Grants is explicitly disabled on an S3 Non-Async Client",
false);
}
private Configuration createConfig(boolean s3agEnabled) {
Configuration conf = new Configuration();
conf.setBoolean(AWS_S3_ACCESS_GRANTS_ENABLED, s3agEnabled);
return conf;
}
private String getCredentialProviderName(AwsClient awsClient) {
return awsClient.serviceClientConfiguration().credentialsProvider().getClass().getName();
}
private AwsClient getAwsClient(Configuration conf, boolean asyncClient)
throws IOException, URISyntaxException {
DefaultS3ClientFactory factory = new DefaultS3ClientFactory();
factory.setConf(conf);
S3ClientFactory.S3ClientCreationParameters parameters =
new S3ClientFactory.S3ClientCreationParameters();
URI uri = new URI("any-uri");
return asyncClient ?
factory.createS3AsyncClient(uri, parameters): factory.createS3Client(uri, parameters);
}
private void assertCredentialProviderClass(
Configuration configuration, boolean asyncClient, String message, boolean shouldMatch)
throws IOException, URISyntaxException {
AwsClient awsClient = getAwsClient(configuration, asyncClient);
AbstractStringAssert<?> assertion =
assertThat(S3_ACCESS_GRANTS_EXPECTED_CREDENTIAL_PROVIDER_CLASS)
.describedAs(message);
if (shouldMatch) {
assertion.isEqualTo(getCredentialProviderName(awsClient));
} else {
assertion.isNotEqualTo(getCredentialProviderName(awsClient));
}
}
}
| TestS3AccessGrantConfiguration |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/sps/ExternalSPSBlockMoveTaskHandler.java | {
"start": 3369,
"end": 7574
} | class ____ implements BlockMoveTaskHandler {
private static final Logger LOG = LoggerFactory
.getLogger(ExternalSPSBlockMoveTaskHandler.class);
private final ExecutorService moveExecutor;
private final CompletionService<BlockMovementAttemptFinished> mCompletionServ;
private final NameNodeConnector nnc;
private final SaslDataTransferClient saslClient;
private final BlockStorageMovementTracker blkMovementTracker;
private Daemon movementTrackerThread;
private final SPSService service;
private final BlockDispatcher blkDispatcher;
private final int maxRetry;
public ExternalSPSBlockMoveTaskHandler(Configuration conf,
NameNodeConnector nnc, SPSService spsService) {
int moverThreads = conf.getInt(DFSConfigKeys.DFS_MOVER_MOVERTHREADS_KEY,
DFSConfigKeys.DFS_MOVER_MOVERTHREADS_DEFAULT);
maxRetry = conf.getInt(
DFSConfigKeys.DFS_STORAGE_POLICY_SATISFIER_MOVE_TASK_MAX_RETRY_ATTEMPTS_KEY,
DFSConfigKeys.DFS_STORAGE_POLICY_SATISFIER_MOVE_TASK_MAX_RETRY_ATTEMPTS_DEFAULT);
moveExecutor = initializeBlockMoverThreadPool(moverThreads);
mCompletionServ = new ExecutorCompletionService<>(moveExecutor);
this.nnc = nnc;
this.saslClient = new SaslDataTransferClient(conf,
DataTransferSaslUtil.getSaslPropertiesResolver(conf),
TrustedChannelResolver.getInstance(conf),
nnc.getFallbackToSimpleAuth());
this.blkMovementTracker = new BlockStorageMovementTracker(
mCompletionServ, new ExternalBlocksMovementsStatusHandler());
this.service = spsService;
boolean connectToDnViaHostname = conf.getBoolean(
HdfsClientConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME,
HdfsClientConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
int ioFileBufferSize = DFSUtilClient.getIoFileBufferSize(conf);
blkDispatcher = new BlockDispatcher(HdfsConstants.READ_TIMEOUT,
ioFileBufferSize, connectToDnViaHostname);
startMovementTracker();
}
/**
* Initializes block movement tracker daemon and starts the thread.
*/
private void startMovementTracker() {
movementTrackerThread = new Daemon(this.blkMovementTracker);
movementTrackerThread.setName("BlockStorageMovementTracker");
movementTrackerThread.start();
}
private ThreadPoolExecutor initializeBlockMoverThreadPool(int num) {
LOG.debug("Block mover to satisfy storage policy; pool threads={}", num);
ThreadPoolExecutor moverThreadPool = new ThreadPoolExecutor(1, num, 60,
TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new Daemon.DaemonFactory() {
private final AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = super.newThread(r);
t.setName("BlockMoverTask-" + threadIndex.getAndIncrement());
return t;
}
}, new ThreadPoolExecutor.CallerRunsPolicy() {
@Override
public void rejectedExecution(Runnable runnable,
ThreadPoolExecutor e) {
LOG.info("Execution for block movement to satisfy storage policy"
+ " got rejected, Executing in current thread");
// will run in the current thread.
super.rejectedExecution(runnable, e);
}
});
moverThreadPool.allowCoreThreadTimeOut(true);
return moverThreadPool;
}
@Override
public void submitMoveTask(BlockMovingInfo blkMovingInfo) throws IOException {
// TODO: Need to increment scheduled block size on the target node. This
// count will be used to calculate the remaining space of target datanode
// during block movement assignment logic. In the internal movement,
// remaining space is bookkeeping at the DatanodeDescriptor, please refer
// IntraSPSNameNodeBlockMoveTaskHandler#submitMoveTask implementation and
// updating via the function call -
// dn.incrementBlocksScheduled(blkMovingInfo.getTargetStorageType());
LOG.debug("Received BlockMovingTask {}", blkMovingInfo);
BlockMovingTask blockMovingTask = new BlockMovingTask(blkMovingInfo);
mCompletionServ.submit(blockMovingTask);
}
private | ExternalSPSBlockMoveTaskHandler |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/Employee.java | {
"start": 526,
"end": 724
} | class ____ {
@Id @GeneratedValue
public long id;
@ManyToMany
public Set<Manager> managers = new HashSet<Manager>();
@ManyToMany
public Set<Employee> friends = new HashSet<Employee>();
}
| Employee |
java | alibaba__nacos | plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySql.java | {
"start": 900,
"end": 1090
} | class ____ extends AbstractMapperByMysql implements TenantInfoMapper {
@Override
public String getDataSource() {
return DataSourceConstant.MYSQL;
}
}
| TenantInfoMapperByMySql |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/DynamicRouter3Test.java | {
"start": 1039,
"end": 2124
} | class ____ extends ContextTestSupport {
@Test
public void testDynamicRouter() throws Exception {
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:b").expectedMessageCount(1);
getMockEndpoint("mock:c").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
// use a bean as the dynamic router
.dynamicRouter().method(DynamicRouter3Test.class, "slip");
}
};
}
public String slip(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) {
if (previous == null) {
return "mock:a,mock:b";
} else if ("mock://b".equals(previous)) {
return "mock:c";
}
// no more so return null
return null;
}
}
| DynamicRouter3Test |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertyTest.java | {
"start": 1622,
"end": 7306
} | class ____ {
@Test
void testEmptyAttribute(@Named("List") final ListAppender app) {
final org.apache.logging.log4j.Logger logger = LogManager.getLogger();
logger.info("msg");
final List<String> messages = app.getMessages();
assertNotNull(messages, "No Messages");
assertEquals(1, messages.size(), "message count" + messages);
// <Property name="emptyElementKey" />
// <Property name="emptyAttributeKey" value="" />
// <Property name="emptyAttributeKey2" value=""></Property>
// <Property name="elementKey">elementValue</Property>
// <Property name="attributeKey" value="attributeValue" />
// <Property name="attributeWithEmptyElementKey" value="attributeValue2"></Property>
// <Property name="bothElementAndAttributeKey" value="attributeValue3">elementValue3</Property>
final String expect = "1=elementValue" + // ${sys:elementKey}
",2="
+ // ${sys:emptyElementKey}
",a="
+ // ${sys:emptyAttributeKey}
",b="
+ // ${sys:emptyAttributeKey2}
",3=attributeValue"
+ // ${sys:attributeKey}
",4=attributeValue2"
+ // ${sys:attributeWithEmptyElementKey}
",5=elementValue3,m=msg"; // ${sys:bothElementAndAttributeKey}
assertEquals(expect, messages.get(0));
app.clear();
}
@Test
void testPropertyValues() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final StrSubstitutor sub = ctx.getConfiguration().getStrSubstitutor();
// <Property name="emptyElementKey" />
// <Property name="emptyAttributeKey" value="" />
// <Property name="emptyAttributeKey2" value=""></Property>
// <Property name="elementKey">elementValue</Property>
// <Property name="attributeKey" value="attributeValue" />
// <Property name="attributeWithEmptyElementKey" value="attributeValue2"></Property>
// <Property name="bothElementAndAttributeKey" value="attributeValue3">elementValue3</Property>
assertEquals("", sub.replace("${emptyElementKey}"));
assertEquals("", sub.replace("${emptyAttributeKey}"));
assertEquals("", sub.replace("${emptyAttributeKey2}"));
assertEquals("elementValue", sub.replace("${elementKey}"));
assertEquals("attributeValue", sub.replace("${attributeKey}"));
assertEquals("attributeValue2", sub.replace("${attributeWithEmptyElementKey}"));
assertEquals("elementValue3", sub.replace("${bothElementAndAttributeKey}"));
}
@Test
void testLoggerPropertyValues() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final List<Property> rootLoggerProperties =
ctx.getConfiguration().getLoggerConfig(LoggerConfig.ROOT).getPropertyList();
// <Property name="emptyElementKey" />
// <Property name="emptyAttributeKey" value="" />
// <Property name="emptyAttributeKey2" value=""></Property>
// <Property name="elementKey">elementValue</Property>
// <Property name="attributeKey" value="attributeValue" />
// <Property name="attributeWithEmptyElementKey" value="attributeValue2"></Property>
// <Property name="bothElementAndAttributeKey" value="attributeValue3">elementValue3</Property>
assertEquals(9, rootLoggerProperties.size());
verifyProperty(rootLoggerProperties.get(0), "emptyElementKey", "", "");
verifyProperty(rootLoggerProperties.get(1), "emptyAttributeKey", "", "");
verifyProperty(rootLoggerProperties.get(2), "emptyAttributeKey2", "", "");
verifyProperty(rootLoggerProperties.get(3), "elementKey", "elementValue", "elementValue");
verifyProperty(rootLoggerProperties.get(4), "attributeKey", "attributeValue", "attributeValue");
verifyProperty(
rootLoggerProperties.get(5), "attributeWithEmptyElementKey", "attributeValue2", "attributeValue2");
verifyProperty(rootLoggerProperties.get(6), "bothElementAndAttributeKey", "elementValue3", "elementValue3");
verifyProperty(rootLoggerProperties.get(7), "attributeWithLookup", "${lower:ATTR}", "attr");
verifyProperty(rootLoggerProperties.get(8), "elementWithLookup", "${lower:ELEMENT}", "element");
}
private static void verifyProperty(
final Property property,
final String expectedName,
final String expectedRawValue,
final String expectedValue) {
assertEquals(expectedName, property.getName());
assertEquals(expectedRawValue, property.getRawValue());
assertEquals(expectedValue, property.getValue());
}
@Test
void testNullValueIsConvertedToEmptyString() { // LOG4J2-1313 <Property name="x" /> support
assertEquals("", Property.createProperty("name", null).getValue());
}
@Test
void testIsValueNeedsLookup() {
assertTrue(Property.createProperty("", "${").isValueNeedsLookup(), "with ${ as value");
assertTrue(Property.createProperty("", "blah${blah").isValueNeedsLookup(), "with ${ in value");
assertFalse(Property.createProperty("", "").isValueNeedsLookup(), "empty value");
assertFalse(Property.createProperty("", "blahblah").isValueNeedsLookup(), "without ${ in value");
assertFalse(Property.createProperty("", "blahb{sys:lah").isValueNeedsLookup(), "without $ in value");
assertFalse(Property.createProperty("", "blahb$sys:lah").isValueNeedsLookup(), "without { in value");
}
}
| PropertyTest |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/httpservice/groups/repeat/EchoService.java | {
"start": 861,
"end": 972
} | interface ____ {
@PostExchange("/echo")
Map<?, ?> echo(@RequestBody Map<String, String> message);
}
| EchoService |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/ClassUtils.java | {
"start": 18304,
"end": 18599
} | class ____ will be quite long, considering that they
// SHOULD sit in a package, so a length check is worthwhile.
if (name != null && name.length() <= 7) {
// Could be a primitive - likely.
result = primitiveTypeNameMap.get(name);
}
return result;
}
/**
* Check if the given | names |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/rest/RestGetInferenceModelAction.java | {
"start": 1191,
"end": 2837
} | class ____ extends BaseRestHandler {
public static final String DEFAULT_ELSER_2_CAPABILITY = "default_elser_2";
@Override
public String getName() {
return "get_inference_model_action";
}
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "_inference"),
new Route(GET, "_inference/_all"),
new Route(GET, INFERENCE_ID_PATH),
new Route(GET, TASK_TYPE_INFERENCE_ID_PATH)
);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {
String inferenceEntityId = null;
TaskType taskType = null;
if (restRequest.hasParam(TASK_TYPE_OR_INFERENCE_ID) == false && restRequest.hasParam(INFERENCE_ID) == false) {
// _all models request
inferenceEntityId = "_all";
taskType = TaskType.ANY;
} else if (restRequest.hasParam(INFERENCE_ID)) {
inferenceEntityId = restRequest.param(INFERENCE_ID);
taskType = TaskType.fromStringOrStatusException(restRequest.param(TASK_TYPE_OR_INFERENCE_ID));
} else {
inferenceEntityId = restRequest.param(TASK_TYPE_OR_INFERENCE_ID);
taskType = TaskType.ANY;
}
var request = new GetInferenceModelAction.Request(inferenceEntityId, taskType);
return channel -> client.execute(GetInferenceModelAction.INSTANCE, request, new RestToXContentListener<>(channel));
}
@Override
public Set<String> supportedCapabilities() {
return Set.of(DEFAULT_ELSER_2_CAPABILITY);
}
}
| RestGetInferenceModelAction |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/AddressBook.java | {
"start": 411,
"end": 996
} | class ____ {
@Id
private Integer id;
@Basic
private String name;
@OrderBy( "last_name" )
@ElementCollection
private Set<Contact> contacts;
private AddressBook() {
// for Hibernate use
}
public AddressBook(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Contact> getContacts() {
return contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
}
| AddressBook |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/EnhancementHelper.java | {
"start": 7318,
"end": 8869
} | enum ____ {
NO_SESSION,
CLOSED_SESSION,
DISCONNECTED_SESSION,
NO_SF_UUID
}
private static LazyInitializationException createLazyInitializationException(final Cause cause, final String entityName, final String attributeName) {
final String reason = switch ( cause ) {
case NO_SESSION -> "no session and settings disallow loading outside the Session";
case CLOSED_SESSION -> "session is closed and settings disallow loading outside the Session";
case DISCONNECTED_SESSION -> "session is disconnected and settings disallow loading outside the Session";
case NO_SF_UUID -> "could not determine SessionFactory UUId to create temporary Session for loading";
};
final String message = String.format(
Locale.ROOT,
"Unable to perform requested lazy initialization [%s.%s] - %s",
entityName,
attributeName,
reason
);
return new LazyInitializationException( message );
}
private static SharedSessionContractImplementor openTemporarySessionForLoading(
BytecodeLazyAttributeInterceptor interceptor,
String entityName,
String attributeName) {
if ( interceptor.getSessionFactoryUuid() == null ) {
throw createLazyInitializationException( Cause.NO_SF_UUID, entityName, attributeName );
}
final var factory = SessionFactoryRegistry.INSTANCE.getSessionFactory( interceptor.getSessionFactoryUuid() );
final var session = factory.openSession();
session.getPersistenceContextInternal().setDefaultReadOnly( true );
session.setHibernateFlushMode( FlushMode.MANUAL );
return session;
}
}
| Cause |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/service/registry/HttpServiceGroupConfigurer.java | {
"start": 1669,
"end": 3093
} | interface ____<CB> {
/**
* Select groups to configure by name.
*/
Groups<CB> filterByName(String... groupNames);
/**
* Select groups to configure through a {@link Predicate}.
*/
Groups<CB> filter(Predicate<HttpServiceGroup> predicate);
/**
* Callback to customize the client builder for every group matched by
* the specified name or predicate filters, or to all groups
* if no filters are specified.
*/
void forEachClient(ClientCallback<CB> callback);
/**
* Callback to supply the client builder for every group matched by
* the specified name or predicate filters, or to all groups
* if no filters are specified.
*/
void forEachClient(InitializingClientCallback<CB> callback);
/**
* Callback to customize the proxy factory for every group matched by
* the specified name or predicate filters, or to all groups
* if no filters are specified.
*/
void forEachProxyFactory(ProxyFactoryCallback callback);
/**
* Callback to customize the client builder and the proxy factory for
* every group matched by the specified name or predicate filters,
* or to all groups if no filters are specified.
*/
void forEachGroup(GroupCallback<CB> callback);
}
/**
* Callback to configure the client for a given group.
* @param <CB> the type of client builder, i.e. {@code RestClient} or {@code WebClient} builder.
*/
@FunctionalInterface
| Groups |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/function/client/aws/LocalFunctionInvokeSpec.java | {
"start": 2841,
"end": 3122
} | interface ____ {
@SingleResult
Publisher<Long> max();
@Named("round")
@SingleResult
Publisher<Integer> rnd(@Body float value);
@SingleResult
Publisher<Long> sum(@Body Sum sum);
}
//end::rxFunctionClient[]
}
| RxMathClient |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java | {
"start": 47355,
"end": 47604
} | interface ____ {
String value() default "";
String qualifier() default "transactionManager";
boolean readOnly() default false;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@ | Transactional |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/AnyGetterTest.java | {
"start": 2217,
"end": 2826
} | class ____ extends StdSerializer<Object>
{
public Issue705Serializer() {
super(Map.class);
}
@Override
public void serialize(Object value, JsonGenerator g, SerializationContext ctxt)
{
StringBuilder sb = new StringBuilder();
for (Map.Entry<?,?> entry : ((Map<?,?>) value).entrySet()) {
sb.append('[').append(entry.getKey()).append('/').append(entry.getValue()).append(']');
}
g.writeStringProperty("stuff", sb.toString());
}
}
// [databind#1124]
static | Issue705Serializer |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BatchFetchReferencedColumnNameTest.java | {
"start": 1794,
"end": 2551
} | class ____ {
@Test
@JiraKey(value = "HHH-13059")
public void test(SessionFactoryScope scope) throws Exception {
scope.inTransaction( session -> {
Parent p = new Parent();
p.setId( 1L );
session.persist( p );
Child c1 = new Child();
c1.setCreatedOn( ZonedDateTime.now() );
c1.setParentId( 1L );
c1.setId( 10L );
session.persist( c1 );
Child c2 = new Child();
c2.setCreatedOn( ZonedDateTime.now() );
c2.setParentId( 1L );
c2.setId( 11L );
session.persist( c2 );
} );
scope.inTransaction( session -> {
Parent p = session.get( Parent.class, 1L );
assertNotNull( p );
assertEquals( 2, p.getChildren().size() );
} );
}
@Entity
@Table(name = "CHILD")
public static | BatchFetchReferencedColumnNameTest |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.java | {
"start": 973,
"end": 1266
} | class ____ implements CompatibleExt {
public String echo(URL url, String s) {
return "Ext1Impl2-echo";
}
public String yell(URL url, String s) {
return "Ext1Impl2-yell";
}
public String bang(URL url, int i) {
return "bang2";
}
}
| CompatibleExtImpl2 |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/hateoas/AbstractResource.java | {
"start": 1629,
"end": 6671
} | class ____<Impl extends AbstractResource<Impl>> implements Resource {
private final Map<CharSequence, List<Link>> linkMap = new LinkedHashMap<>(1);
private final Map<CharSequence, List<Resource>> embeddedMap = new LinkedHashMap<>(1);
/**
* Add a link with the given reference.
*
* @param ref The reference
* @param link The link
* @return This JsonError
*/
public Impl link(@Nullable CharSequence ref, @Nullable Link link) {
if (StringUtils.isNotEmpty(ref) && link != null) {
List<Link> links = this.linkMap.computeIfAbsent(ref, charSequence -> new ArrayList<>());
links.add(link);
}
return (Impl) this;
}
/**
* Add a link with the given reference.
*
* @param ref The reference
* @param link The link
* @return This JsonError
*/
public Impl link(@Nullable CharSequence ref, @Nullable String link) {
if (StringUtils.isNotEmpty(ref) && link != null) {
List<Link> links = this.linkMap.computeIfAbsent(ref, charSequence -> new ArrayList<>());
links.add(Link.of(link));
}
return (Impl) this;
}
/**
* Add an embedded resource with the given reference.
*
* @param ref The reference
* @param resource The resource
* @return This JsonError
*/
public Impl embedded(CharSequence ref, Resource resource) {
if (StringUtils.isNotEmpty(ref) && resource != null) {
List<Resource> resources = this.embeddedMap.computeIfAbsent(ref, charSequence -> new ArrayList<>());
resources.add(resource);
}
return (Impl) this;
}
/**
* Add an embedded resource with the given reference.
*
* @param ref The reference
* @param resource The resource
* @return This JsonError
*/
public Impl embedded(CharSequence ref, Resource... resource) {
if (StringUtils.isNotEmpty(ref) && resource != null) {
List<Resource> resources = this.embeddedMap.computeIfAbsent(ref, charSequence -> new ArrayList<>());
resources.addAll(Arrays.asList(resource));
}
return (Impl) this;
}
/**
* Add an embedded resource with the given reference.
*
* @param ref The reference
* @param resourceList The resources
* @return This JsonError
*/
public Impl embedded(CharSequence ref, List<Resource> resourceList) {
if (StringUtils.isNotEmpty(ref) && resourceList != null) {
List<Resource> resources = this.embeddedMap.computeIfAbsent(ref, charSequence -> new ArrayList<>());
resources.addAll(resourceList);
}
return (Impl) this;
}
@JsonProperty(LINKS)
@Override
public OptionalMultiValues<Link> getLinks() {
return OptionalMultiValues.of(linkMap);
}
@JsonProperty(EMBEDDED)
@Override
public OptionalMultiValues<Resource> getEmbedded() {
return OptionalMultiValues.of(embeddedMap);
}
/**
* Allows de-serializing of links with Jackson.
*
* @param links The links
*/
@SuppressWarnings("unchecked")
@Internal
@ReflectiveAccess
@JsonProperty(LINKS)
public final void setLinks(Map<String, Object> links) {
for (Map.Entry<String, Object> entry : links.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
Map<String, Object> linkMap = (Map<String, Object>) value;
link(name, linkMap);
} else if (value instanceof Collection<?> collection) {
for (Object o : collection) {
if (o instanceof Map aMap) {
link(name, aMap);
}
}
}
}
}
/**
* Allows de-serializing of embedded with Jackson.
*
* @param embedded The links
*/
@Internal
@ReflectiveAccess
@JsonProperty(EMBEDDED)
public final void setEmbedded(Map<String, List<Resource>> embedded) {
this.embeddedMap.putAll(embedded);
}
private void link(String name, Map<String, Object> linkMap) {
ConvertibleValues<Object> values = ConvertibleValues.of(linkMap);
Optional<String> uri = values.get(Link.HREF, String.class);
uri.ifPresent(uri1 -> {
Link.Builder link = Link.build(uri1);
values.get("templated", Boolean.class)
.ifPresent(link::templated);
values.get("hreflang", String.class)
.ifPresent(link::hreflang);
values.get("title", String.class)
.ifPresent(link::title);
values.get("profile", String.class)
.ifPresent(link::profile);
values.get("deprecation", String.class)
.ifPresent(link::deprecation);
link(name, link.build());
});
}
}
| AbstractResource |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/method/configuration/PrePostMethodSecurityConfigurationTests.java | {
"start": 71237,
"end": 71525
} | class ____ {
@Bean
AnnotationTemplateExpressionDefaults methodSecurityDefaults() {
return new AnnotationTemplateExpressionDefaults();
}
@Bean
MetaAnnotationService metaAnnotationService() {
return new MetaAnnotationService();
}
}
static | MetaAnnotationPlaceholderConfig |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxHttpRequest.java | {
"start": 9888,
"end": 15752
} | class ____ extends AbstractAsynchronousResponse {
private final Object responseLock = new Object();
private long timerID = -1;
private VertxHttpResponse vertxResponse;
VertxHttpAsyncResponse(final SynchronousDispatcher dispatcher, final VertxHttpRequest request,
final VertxHttpResponse response) {
super(dispatcher, request, response);
this.vertxResponse = response;
}
@Override
public void initialRequestThreadFinished() {
// done
}
@Override
public void complete() {
synchronized (responseLock) {
if (done || cancelled) {
return;
}
done = true;
requestContext.activate(requestContextState);
requestContext.terminate();
if (BlockingOperationControl.isBlockingAllowed()) {
vertxFlush();
} else {
executor.execute(new Runnable() {
@Override
public void run() {
vertxFlush();
}
});
}
}
}
@Override
public boolean resume(Object entity) {
synchronized (responseLock) {
if (done)
return false;
if (cancelled)
return false;
done = true;
requestContext.activate(requestContextState);
return internalResume(entity, new FlushTask());
}
}
@Override
public boolean resume(Throwable ex) {
synchronized (responseLock) {
if (done)
return false;
if (cancelled)
return false;
done = true;
requestContext.activate(requestContextState);
return internalResume(ex, new FlushTask());
}
}
@Override
public boolean cancel() {
synchronized (responseLock) {
if (cancelled) {
return true;
}
if (done) {
return false;
}
done = true;
cancelled = true;
requestContext.activate(requestContextState);
return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).build(), new FlushTask());
}
}
@Override
public boolean cancel(int retryAfter) {
synchronized (responseLock) {
if (cancelled)
return true;
if (done)
return false;
done = true;
cancelled = true;
requestContext.activate(requestContextState);
return internalResume(
Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter)
.build(),
new FlushTask());
}
}
protected synchronized void vertxFlush() {
try {
vertxResponse.finish();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean cancel(Date retryAfter) {
synchronized (responseLock) {
if (cancelled)
return true;
if (done)
return false;
done = true;
cancelled = true;
requestContext.activate(requestContextState);
try {
return internalResume(
Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter)
.build(),
t -> vertxFlush());
} finally {
requestContext.terminate();
}
}
}
@Override
public boolean isSuspended() {
return !done && !cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isDone() {
return done;
}
@Override
public boolean setTimeout(long time, TimeUnit unit) {
synchronized (responseLock) {
if (done || cancelled)
return false;
if (timerID > -1 && !context.owner().cancelTimer(timerID)) {
return false;
}
timerID = context.owner().setTimer(unit.toMillis(time), v -> handleTimeout());
}
return true;
}
protected void handleTimeout() {
if (timeoutHandler != null) {
timeoutHandler.handleTimeout(this);
}
if (done)
return;
resume(new ServiceUnavailableException());
}
private | VertxHttpAsyncResponse |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/OverloadedTestMethodTests.java | {
"start": 1011,
"end": 2622
} | class ____ extends AbstractJupiterTestEngineTests {
@Test
void executeTestCaseWithOverloadedMethodsAndThenRerunOnlyOneOfTheMethodsSelectedByUniqueId() {
Events tests = executeTestsForClass(TestCase.class).testEvents();
tests.assertStatistics(stats -> stats.started(2).succeeded(2).failed(0));
Optional<Event> first = tests.succeeded().filter(
event -> event.getTestDescriptor().getUniqueId().toString().contains(TestInfo.class.getName())).findFirst();
assertTrue(first.isPresent());
TestIdentifier testIdentifier = TestIdentifier.from(first.get().getTestDescriptor());
UniqueId uniqueId = testIdentifier.getUniqueIdObject();
tests = executeTests(selectUniqueId(uniqueId)).testEvents();
tests.assertStatistics(stats -> stats.started(1).succeeded(1).failed(0));
first = tests.succeeded().filter(
event -> event.getTestDescriptor().getUniqueId().toString().contains(TestInfo.class.getName())).findFirst();
assertTrue(first.isPresent());
}
@Test
void executeTestCaseWithOverloadedMethodsWithSingleMethodThatAcceptsArgumentsSelectedByFullyQualifiedMethodName() {
String fqmn = TestCase.class.getName() + "#test(" + TestInfo.class.getName() + ")";
Events tests = executeTests(selectMethod(fqmn)).testEvents();
tests.assertStatistics(stats -> stats.started(1).succeeded(1).failed(0));
Optional<Event> first = tests.succeeded().stream().filter(
event -> event.getTestDescriptor().getUniqueId().toString().contains(TestInfo.class.getName())).findFirst();
assertTrue(first.isPresent());
}
@SuppressWarnings("JUnitMalformedDeclaration")
static | OverloadedTestMethodTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/json/SQLServerJsonRemoveFunction.java | {
"start": 521,
"end": 1174
} | class ____ extends AbstractJsonRemoveFunction {
public SQLServerJsonRemoveFunction(TypeConfiguration typeConfiguration) {
super( typeConfiguration );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> translator) {
final Expression json = (Expression) arguments.get( 0 );
final Expression jsonPath = (Expression) arguments.get( 1 );
sqlAppender.appendSql( "json_modify(" );
json.accept( translator );
sqlAppender.appendSql( ',' );
jsonPath.accept( translator );
sqlAppender.appendSql( ",null)" );
}
}
| SQLServerJsonRemoveFunction |
java | apache__maven | compat/maven-model/src/test/java/org/apache/maven/model/ActivationPropertyTest.java | {
"start": 1107,
"end": 1719
} | class ____ {
@Test
void testHashCodeNullSafe() {
new ActivationProperty().hashCode();
}
@Test
void testEqualsNullSafe() {
assertFalse(new ActivationProperty().equals(null));
new ActivationProperty().equals(new ActivationProperty());
}
@Test
void testEqualsIdentity() {
ActivationProperty thing = new ActivationProperty();
assertTrue(thing.equals(thing), "Expected " + thing + " to equal " + thing);
}
@Test
void testToStringNullSafe() {
assertNotNull(new ActivationProperty().toString());
}
}
| ActivationPropertyTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/intarray/IntArrayAssert_containsExactlyInAnyOrder_Test.java | {
"start": 1061,
"end": 1561
} | class ____ extends IntArrayAssertBaseTest {
@Override
protected IntArrayAssert invoke_api_method() {
return assertions.containsExactlyInAnyOrder(1, 2);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContainsExactlyInAnyOrder(getInfo(assertions), getActual(assertions), arrayOf(1, 2));
}
@Test
void invoke_api_like_user() {
assertThat(new int[] { 1, 2, 2 }).containsExactlyInAnyOrder(2, 2, 1);
}
}
| IntArrayAssert_containsExactlyInAnyOrder_Test |
java | spring-projects__spring-boot | module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/DataSourceTransactionManagerAutoConfiguration.java | {
"start": 2483,
"end": 2637
} | class ____ {
@Configuration(proxyBeanMethods = false)
@ConditionalOnSingleCandidate(DataSource.class)
static | DataSourceTransactionManagerAutoConfiguration |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/type/filter/RegexPatternTypeFilter.java | {
"start": 853,
"end": 972
} | class ____ with a regex {@link Pattern}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @since 2.5
*/
public | name |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/node/BigIntegerNode.java | {
"start": 401,
"end": 9886
} | class ____
extends NumericIntNode
{
private static final long serialVersionUID = 3L;
final protected BigInteger _value;
/*
/**********************************************************
/* Construction
/**********************************************************
*/
public BigIntegerNode(BigInteger v) {
// 01-Mar-2024, tatu: [databind#4381] No null-valued JsonNodes
_value = Objects.requireNonNull(v);
}
public static BigIntegerNode valueOf(BigInteger v) { return new BigIntegerNode(v); }
/*
/**********************************************************************
/* Overridden JsonNode methods, simple properties
/**********************************************************************
*/
@Override
public JsonParser.NumberType numberType() { return JsonParser.NumberType.BIG_INTEGER; }
@Override
public boolean isBigInteger() { return true; }
/*
/**********************************************************************
/* Overridden JsonNode methods, scalar access
/**********************************************************************
*/
@Override
protected Boolean _asBoolean() {
return !BigInteger.ZERO.equals(_value);
}
@Override
public String _asString() {
return _value.toString();
}
@Override
public Number numberValue() {
return _value;
}
@Override
public short shortValue() {
if (inShortRange()) {
return _value.shortValue();
}
return _reportShortCoercionRangeFail("shortValue()");
}
@Override
public short shortValue(short defaultValue) {
return inShortRange() ? _value.shortValue() : defaultValue;
}
@Override
public Optional<Short> shortValueOpt() {
return inShortRange() ? Optional.of(_value.shortValue()) : Optional.empty();
}
@Override
public short asShort() {
if (inShortRange()) {
return _value.shortValue();
}
return _reportShortCoercionRangeFail("asShort()");
}
@Override
public short asShort(short defaultValue) {
return inShortRange() ? _value.shortValue() : defaultValue;
}
@Override
public Optional<Short> asShortOpt() {
return inShortRange() ? Optional.of(_value.shortValue()) : Optional.empty();
}
@Override
public int intValue() {
if (inIntRange()) {
return _value.intValue();
}
return _reportIntCoercionRangeFail("intValue()");
}
@Override
public int intValue(int defaultValue) {
return inIntRange() ? _value.intValue() : defaultValue;
}
@Override
public OptionalInt intValueOpt() {
return inIntRange() ? OptionalInt.of(_value.intValue()) : OptionalInt.empty();
}
@Override
public int asInt() {
if (inIntRange()) {
return _value.intValue();
}
return _reportIntCoercionRangeFail("asInt()");
}
@Override
public int asInt(int defaultValue) {
return inIntRange() ? _value.intValue() : defaultValue;
}
@Override
public OptionalInt asIntOpt() {
return inIntRange() ? OptionalInt.of(_value.intValue()) : OptionalInt.empty();
}
@Override
public long longValue() {
if (canConvertToLong()) {
return _value.longValue();
}
return _reportLongCoercionRangeFail("longValue()");
}
@Override
public long longValue(long defaultValue) {
return (canConvertToLong()) ? _value.longValue() : defaultValue;
}
@Override
public OptionalLong longValueOpt() {
return canConvertToLong() ? OptionalLong.of(_value.longValue()) : OptionalLong.empty();
}
@Override
public long asLong() {
if (canConvertToLong()) {
return _value.longValue();
}
return _reportLongCoercionRangeFail("asLong()");
}
@Override
public long asLong(long defaultValue) {
return (canConvertToLong()) ? _value.longValue() : defaultValue;
}
@Override
public OptionalLong asLongOpt() {
return canConvertToLong() ? OptionalLong.of(_value.longValue()) : OptionalLong.empty();
}
@Override
public BigInteger bigIntegerValue() { return _value; }
@Override
public BigInteger bigIntegerValue(BigInteger defaultValue) { return _value; }
@Override
public Optional<BigInteger> bigIntegerValueOpt() { return Optional.of(_value); }
// // // BigInteger differs a bit from other Integral types as there's
// // // range overflow possibility
@Override
public float floatValue() {
float f = _asFloatValueUnchecked();
if (Float.isFinite(f)) {
return f;
}
return _reportFloatCoercionRangeFail("floatValue()");
}
@Override
public float floatValue(float defaultValue) {
float f = _asFloatValueUnchecked();
return (Float.isFinite(f)) ? f : defaultValue;
}
@Override
public Optional<Float> floatValueOpt() {
float f = _asFloatValueUnchecked();
if (Float.isFinite(f)) {
return Optional.of(f);
}
return Optional.empty();
}
@Override
public float asFloat() {
float f = _asFloatValueUnchecked();
if (Float.isFinite(f)) {
return f;
}
return _reportFloatCoercionRangeFail("asFloat()");
}
@Override
public float asFloat(float defaultValue) {
float f = _asFloatValueUnchecked();
return (Float.isFinite(f)) ? f : defaultValue;
}
@Override
public Optional<Float> asFloatOpt() {
float f = _asFloatValueUnchecked();
if (Float.isFinite(f)) {
return Optional.of(f);
}
return Optional.empty();
}
@Override
public double doubleValue() {
double d = _asDoubleValueUnchecked();
if (Double.isFinite(d)) {
return d;
}
return _reportDoubleCoercionRangeFail("doubleValue()");
}
@Override
public double doubleValue(double defaultValue) {
double d = _asDoubleValueUnchecked();
return (Double.isFinite(d)) ? d : defaultValue;
}
@Override
public OptionalDouble doubleValueOpt() {
double d = _asDoubleValueUnchecked();
if (Double.isFinite(d)) {
return OptionalDouble.of(d);
}
return OptionalDouble.empty();
}
@Override
public double asDouble() {
double d = _asDoubleValueUnchecked();
if (Double.isFinite(d)) {
return d;
}
return _reportDoubleCoercionRangeFail("asDouble()");
}
@Override
public double asDouble(double defaultValue) {
double d = _asDoubleValueUnchecked();
return (Double.isFinite(d)) ? d : defaultValue;
}
@Override
public OptionalDouble asDoubleOpt() {
double d = _asDoubleValueUnchecked();
if (Double.isFinite(d)) {
return OptionalDouble.of(d);
}
return OptionalDouble.empty();
}
@Override
public BigDecimal decimalValue() {
return new BigDecimal(_value);
}
@Override
public BigDecimal decimalValue(BigDecimal defaultValue) {
return new BigDecimal(_value);
}
@Override
public Optional<BigDecimal> decimalValueOpt() {
return Optional.of(new BigDecimal(_value));
}
/*
/**********************************************************************
/* Abstract methods impls for NumericIntNode
/**********************************************************************
*/
@Override
public short _asShortValueUnchecked() {
return _value.shortValue();
}
@Override
public int _asIntValueUnchecked() {
return _value.intValue();
}
@Override
public long _asLongValueUnchecked() {
return _value.longValue();
}
@Override
protected float _asFloatValueUnchecked() {
return _value.floatValue();
}
@Override
protected double _asDoubleValueUnchecked() {
return _value.doubleValue();
}
@Override
public boolean inShortRange() {
return (_value.compareTo(BI_MIN_SHORT) >= 0)
&& (_value.compareTo(BI_MAX_SHORT) <= 0);
}
@Override
public boolean inIntRange() {
return (_value.compareTo(BI_MIN_INTEGER) >= 0)
&& (_value.compareTo(BI_MAX_INTEGER) <= 0);
}
@Override
public boolean inLongRange() {
return (_value.compareTo(BI_MIN_LONG) >= 0)
&& (_value.compareTo(BI_MAX_LONG) <= 0);
}
/*
/**********************************************************************
/* Other overrides
/**********************************************************************
*/
@Override
public final void serialize(JsonGenerator g, SerializationContext provider)
throws JacksonException
{
g.writeNumber(_value);
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o instanceof BigIntegerNode otherNode) {
return Objects.equals(otherNode._value, _value);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(_value);
}
}
| BigIntegerNode |
java | apache__flink | flink-filesystems/flink-s3-fs-base/src/test/java/org/apache/flink/fs/s3/common/writer/RecoverableMultiPartUploadImplTest.java | {
"start": 15512,
"end": 16814
} | class ____ extends UploadPartResult {
private static final long serialVersionUID = 1L;
private byte[] content;
void setContent(byte[] content) {
this.content = content;
}
public byte[] getContent() {
return content;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TestUploadPartResult that = (TestUploadPartResult) o;
return getETag().equals(that.getETag())
&& getPartNumber() == that.getPartNumber()
&& Arrays.equals(content, that.content);
}
@Override
public int hashCode() {
return 31 * Objects.hash(getETag(), getPartNumber()) + Arrays.hashCode(getContent());
}
@Override
public String toString() {
return '{'
+ "etag="
+ getETag()
+ ", partNo="
+ getPartNumber()
+ ", content="
+ Arrays.toString(content)
+ '}';
}
}
}
| TestUploadPartResult |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/BeanWithHeadersAndBodyInjectionTest.java | {
"start": 2680,
"end": 3285
} | class ____ {
public Map<String, Object> headers;
public Object body;
@Override
public String toString() {
return "MyBean[foo: " + headers + " body: " + body + "]";
}
public void myMethod(@Headers Map<String, Object> headers, Object body) {
this.headers = headers;
this.body = body;
LOG.info("myMethod() method called on {}", this);
}
public void anotherMethod(@Headers Map<String, Object> headers, Object body) {
fail("Should not have called this method!");
}
}
}
| MyBean |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/util/TypeKey.java | {
"start": 281,
"end": 3272
} | class ____
{
protected int _hashCode;
protected Class<?> _class;
protected JavaType _type;
/**
* Indicator of whether serializer stored has a type serializer
* wrapper around it or not; if not, it is "untyped" serializer;
* if it has, it is "typed"
*/
protected boolean _isTyped;
public TypeKey() { }
public TypeKey(TypeKey src) {
_hashCode = src._hashCode;
_class = src._class;
_type = src._type;
_isTyped = src._isTyped;
}
public TypeKey(Class<?> key, boolean typed) {
_class = key;
_type = null;
_isTyped = typed;
_hashCode = typed ? typedHash(key) : untypedHash(key);
}
public TypeKey(JavaType key, boolean typed) {
_type = key;
_class = null;
_isTyped = typed;
_hashCode = typed ? typedHash(key) : untypedHash(key);
}
public final static int untypedHash(Class<?> cls) {
return cls.getName().hashCode();
}
public final static int typedHash(Class<?> cls) {
return cls.getName().hashCode()+1;
}
public final static int untypedHash(JavaType type) {
return type.hashCode() - 1;
}
public final static int typedHash(JavaType type) {
return type.hashCode() - 2;
}
public final void resetTyped(Class<?> cls) {
_type = null;
_class = cls;
_isTyped = true;
_hashCode = typedHash(cls);
}
public final void resetUntyped(Class<?> cls) {
_type = null;
_class = cls;
_isTyped = false;
_hashCode = untypedHash(cls);
}
public final void resetTyped(JavaType type) {
_type = type;
_class = null;
_isTyped = true;
_hashCode = typedHash(type);
}
public final void resetUntyped(JavaType type) {
_type = type;
_class = null;
_isTyped = false;
_hashCode = untypedHash(type);
}
public boolean isTyped() {
return _isTyped;
}
public Class<?> getRawType() {
return _class;
}
public JavaType getType() {
return _type;
}
@Override public final int hashCode() { return _hashCode; }
@Override public final String toString() {
if (_class != null) {
return "{class: "+_class.getName()+", typed? "+_isTyped+"}";
}
return "{type: "+_type+", typed? "+_isTyped+"}";
}
// note: we assume key is never used for anything other than as map key, so:
@Override public final boolean equals(Object o)
{
if (o == null) return false;
if (o == this) return true;
if (o.getClass() != getClass()) {
return false;
}
TypeKey other = (TypeKey) o;
if (other._isTyped == _isTyped) {
if (_class != null) {
return other._class == _class;
}
return _type.equals(other._type);
}
return false;
}
} | TypeKey |
java | spring-projects__spring-framework | spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/init/H2DatabasePopulatorIntegrationTests.java | {
"start": 878,
"end": 1256
} | class ____ extends AbstractDatabasePopulatorTests {
UUID databaseName = UUID.randomUUID();
ConnectionFactory connectionFactory = ConnectionFactories.get(
"r2dbc:h2:mem:///" + databaseName + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
@Override
ConnectionFactory getConnectionFactory() {
return this.connectionFactory;
}
}
| H2DatabasePopulatorIntegrationTests |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java | {
"start": 1185,
"end": 1621
} | interface ____ extends java.io.Serializable {
/**
* @return the URL for the saved request, allowing a redirect to be performed.
*/
String getRedirectUrl();
List<Cookie> getCookies();
String getMethod();
List<String> getHeaderValues(String name);
Collection<String> getHeaderNames();
List<Locale> getLocales();
String @Nullable [] getParameterValues(String name);
Map<String, String[]> getParameterMap();
}
| SavedRequest |
java | apache__flink | flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesJobManagerParametersTest.java | {
"start": 2061,
"end": 12387
} | class ____ extends KubernetesTestBase {
private static final double JOB_MANAGER_CPU = 2.0;
private static final double JOB_MANAGER_CPU_LIMIT_FACTOR = 2.5;
private static final double JOB_MANAGER_MEMORY_LIMIT_FACTOR = 2.0;
private final ClusterSpecification clusterSpecification =
new ClusterSpecification.ClusterSpecificationBuilder()
.setMasterMemoryMB(JOB_MANAGER_MEMORY)
.setTaskManagerMemoryMB(1024)
.setSlotsPerTaskManager(1)
.createClusterSpecification();
private final KubernetesJobManagerParameters kubernetesJobManagerParameters =
new KubernetesJobManagerParameters(flinkConfig, clusterSpecification);
@Test
void testGetEnvironments() {
final Map<String, String> expectedEnvironments = new HashMap<>();
expectedEnvironments.put("k1", "v1");
expectedEnvironments.put("k2", "v2");
expectedEnvironments.forEach(
(k, v) ->
flinkConfig.setString(
ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX + k, v));
final Map<String, String> resultEnvironments =
kubernetesJobManagerParameters.getEnvironments();
assertThat(resultEnvironments).isEqualTo(expectedEnvironments);
}
@Test
void testGetEmptyAnnotations() {
assertThat(kubernetesJobManagerParameters.getAnnotations()).isEmpty();
}
@Test
void testGetJobManagerAnnotations() {
final Map<String, String> expectedAnnotations = new HashMap<>();
expectedAnnotations.put("a1", "v1");
expectedAnnotations.put("a2", "v2");
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_ANNOTATIONS, expectedAnnotations);
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getAnnotations();
assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
void testGetRestServiceAnnotations() {
final Map<String, String> expectedAnnotations = Map.of("a1", "v1", "a2", "v2");
flinkConfig.set(KubernetesConfigOptions.REST_SERVICE_ANNOTATIONS, expectedAnnotations);
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getRestServiceAnnotations();
assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
void testGetRestServiceLabels() {
final Map<String, String> expectedLabels = Map.of("a1", "v1", "a2", "v2");
flinkConfig.set(KubernetesConfigOptions.REST_SERVICE_LABELS, expectedLabels);
final Map<String, String> resultLabels =
kubernetesJobManagerParameters.getRestServiceLabels();
assertThat(resultLabels).isEqualTo(expectedLabels);
}
@Test
void testGetInternalServiceAnnotations() {
final Map<String, String> expectedAnnotations = new HashMap<>();
expectedAnnotations.put("a1", "v1");
expectedAnnotations.put("a2", "v2");
flinkConfig.set(KubernetesConfigOptions.INTERNAL_SERVICE_ANNOTATIONS, expectedAnnotations);
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getInternalServiceAnnotations();
assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
void testGetInternalServiceLabels() {
final Map<String, String> expectedLabels = new HashMap<>();
expectedLabels.put("a1", "v1");
expectedLabels.put("a2", "v2");
flinkConfig.set(KubernetesConfigOptions.INTERNAL_SERVICE_LABELS, expectedLabels);
final Map<String, String> resultLabels =
kubernetesJobManagerParameters.getInternalServiceLabels();
assertThat(resultLabels).isEqualTo(expectedLabels);
}
@Test
void testGetJobManagerMemoryMB() {
assertThat(kubernetesJobManagerParameters.getJobManagerMemoryMB())
.isEqualTo(JOB_MANAGER_MEMORY);
}
@Test
void testGetJobManagerCPU() {
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_CPU, JOB_MANAGER_CPU);
assertThat(kubernetesJobManagerParameters.getJobManagerCPU())
.isEqualTo(JOB_MANAGER_CPU, within(0.00001));
}
@Test
void testGetJobManagerCPULimitFactor() {
flinkConfig.set(
KubernetesConfigOptions.JOB_MANAGER_CPU_LIMIT_FACTOR, JOB_MANAGER_CPU_LIMIT_FACTOR);
assertThat(kubernetesJobManagerParameters.getJobManagerCPULimitFactor())
.isEqualTo(JOB_MANAGER_CPU_LIMIT_FACTOR, within(0.00001));
}
@Test
void testGetJobManagerMemoryLimitFactor() {
flinkConfig.set(
KubernetesConfigOptions.JOB_MANAGER_MEMORY_LIMIT_FACTOR,
JOB_MANAGER_MEMORY_LIMIT_FACTOR);
assertThat(kubernetesJobManagerParameters.getJobManagerMemoryLimitFactor())
.isEqualTo(JOB_MANAGER_MEMORY_LIMIT_FACTOR, within(0.00001));
}
@Test
void testGetRestPort() {
flinkConfig.set(RestOptions.PORT, 12345);
assertThat(kubernetesJobManagerParameters.getRestPort()).isEqualTo(12345);
}
@Test
void testGetRpcPort() {
flinkConfig.set(JobManagerOptions.PORT, 1234);
assertThat(kubernetesJobManagerParameters.getRPCPort()).isEqualTo(1234);
}
@Test
void testGetBlobServerPort() {
flinkConfig.set(BlobServerOptions.PORT, "2345");
assertThat(kubernetesJobManagerParameters.getBlobServerPort()).isEqualTo(2345);
}
@Test
void testGetBlobServerPortException1() {
flinkConfig.set(BlobServerOptions.PORT, "1000-2000");
String errMsg =
BlobServerOptions.PORT.key()
+ " should be specified to a fixed port. Do not support a range of ports.";
assertThatThrownBy(
() -> kubernetesJobManagerParameters.getBlobServerPort(),
"Should fail with an exception.")
.satisfies(
cause ->
assertThat(cause)
.isInstanceOf(FlinkRuntimeException.class)
.hasMessageMatching(errMsg));
}
@Test
void testGetBlobServerPortException2() {
flinkConfig.set(BlobServerOptions.PORT, "0");
assertThatThrownBy(
() -> kubernetesJobManagerParameters.getBlobServerPort(),
"Should fail with an exception.")
.satisfies(
cause ->
assertThat(cause)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageMatching(
BlobServerOptions.PORT.key()
+ " should not be 0."));
}
@Test
void testGetServiceAccount() {
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT, "flink");
assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink");
}
@Test
void testGetServiceAccountFallback() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_SERVICE_ACCOUNT, "flink-fallback");
assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink-fallback");
}
@Test
void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() {
assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("default");
}
@Test
void testGetEntrypointMainClass() {
final String entrypointClass = "org.flink.kubernetes.Entrypoint";
flinkConfig.set(KubernetesConfigOptionsInternal.ENTRY_POINT_CLASS, entrypointClass);
assertThat(kubernetesJobManagerParameters.getEntrypointClass()).isEqualTo(entrypointClass);
}
@Test
void testGetRestServiceExposedType() {
flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.NodePort);
assertThat(kubernetesJobManagerParameters.getRestServiceExposedType())
.isEqualByComparingTo(KubernetesConfigOptions.ServiceExposedType.NodePort);
}
@Test
void testPrioritizeBuiltInLabels() {
final Map<String, String> userLabels = new HashMap<>();
userLabels.put(Constants.LABEL_TYPE_KEY, "user-label-type");
userLabels.put(Constants.LABEL_APP_KEY, "user-label-app");
userLabels.put(Constants.LABEL_COMPONENT_KEY, "user-label-component-jm");
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_LABELS, userLabels);
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
assertThat(kubernetesJobManagerParameters.getLabels()).isEqualTo(expectedLabels);
}
@Test
public void testGetReplicasWithTwoShouldFailWhenHAIsNotEnabled() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 2);
assertThatThrownBy(() -> kubernetesJobManagerParameters.getReplicas())
.isInstanceOf(IllegalConfigurationException.class);
}
@Test
public void testGetReplicasWithInvalidValue() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 0);
assertThatThrownBy(() -> kubernetesJobManagerParameters.getReplicas())
.isInstanceOf(IllegalConfigurationException.class);
}
@Test
void testGetReplicas() {
flinkConfig.set(HighAvailabilityOptions.HA_MODE, HighAvailabilityMode.KUBERNETES.name());
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 2);
assertThat(kubernetesJobManagerParameters.getReplicas()).isEqualTo(2);
}
@Test
public void testGetUserArtifactsBaseDir() {
flinkConfig.set(ArtifactFetchOptions.BASE_DIR, "/opt/job/artifacts");
assertThat(kubernetesJobManagerParameters.getUserArtifactsBaseDir())
.isEqualTo("/opt/job/artifacts");
}
}
| KubernetesJobManagerParametersTest |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java | {
"start": 14309,
"end": 14649
} | class ____.
* <p>This method explicitly handles class-level annotations which are not
* declared as {@linkplain java.lang.annotation.Inherited inherited} <em>as
* well as meta-annotations</em>.
* <p>The algorithm operates as follows:
* <ol>
* <li>Search for a local declaration of one of the annotation types on the
* given | itself |
java | hibernate__hibernate-orm | tooling/hibernate-ant/src/main/java/org/hibernate/tool/hbm2ddl/ConnectionHelper.java | {
"start": 480,
"end": 951
} | interface ____ {
/**
* Prepare the helper for use.
*
* @param needsAutoCommit Should connection be forced to auto-commit
* if not already.
*/
void prepare(boolean needsAutoCommit) throws SQLException;
/**
* Get a reference to the connection we are using.
*
* @return The JDBC connection.
*/
Connection getConnection() throws SQLException;
/**
* Release any resources held by this helper.
*/
void release() throws SQLException;
}
| ConnectionHelper |
java | elastic__elasticsearch | modules/dot-prefix-validation/src/main/java/org/elasticsearch/validation/DotPrefixValidationPlugin.java | {
"start": 961,
"end": 2029
} | class ____ extends Plugin implements ActionPlugin {
private final AtomicReference<List<MappedActionFilter>> actionFilters = new AtomicReference<>();
public DotPrefixValidationPlugin() {}
@Override
public Collection<?> createComponents(PluginServices services) {
ThreadContext context = services.threadPool().getThreadContext();
ClusterService clusterService = services.clusterService();
actionFilters.set(
List.of(
new CreateIndexDotValidator(context, clusterService),
new AutoCreateDotValidator(context, clusterService),
new IndexTemplateDotValidator(context, clusterService)
)
);
return Set.of();
}
@Override
public Collection<MappedActionFilter> getMappedActionFilters() {
return actionFilters.get();
}
@Override
public List<Setting<?>> getSettings() {
return List.of(DotPrefixValidator.VALIDATE_DOT_PREFIXES, DotPrefixValidator.IGNORED_INDEX_PATTERNS_SETTING);
}
}
| DotPrefixValidationPlugin |
java | apache__camel | test-infra/camel-test-infra-pinecone/src/main/java/org/apache/camel/test/infra/pinecone/services/PineconeLocalContainerInfraService.java | {
"start": 2435,
"end": 4527
} | class ____ extends PineconeLocalContainer {
public TestInfraPineconeLocalContainer(boolean fixedPort) {
super(DockerImageName.parse(imageName)
.asCompatibleSubstituteFor("pinecone-io/pinecone-local"));
withStartupTimeout(Duration.ofMinutes(3L));
if (fixedPort) {
addFixedExposedPort(5080, 5080);
}
}
}
return new TestInfraPineconeLocalContainer(ContainerEnvironmentUtil.isFixedPort(this.getClass()));
}
@Override
public void registerProperties() {
System.setProperty(PineconeProperties.PINECONE_ENDPOINT_URL, getPineconeEndpointUrl());
System.setProperty(PineconeProperties.PINECONE_ENDPOINT_HOST, getPineconeHost());
System.setProperty(PineconeProperties.PINECONE_ENDPOINT_PORT, String.valueOf(getPineconePort()));
}
@Override
public void initialize() {
LOG.info("Trying to start the Pinecone container");
container.start();
registerProperties();
LOG.info("Pinecone instance running at {}", getPineconeEndpointUrl());
}
@Override
public void shutdown() {
LOG.info("Stopping the Pinecone container");
container.stop();
}
@Override
public PineconeLocalContainer getContainer() {
return container;
}
@Override
public String getPineconeEndpointUrl() {
return container.getEndpoint();
}
@Override
public String getPineconeHost() {
URL url = null;
try {
url = URI.create(container.getEndpoint()).toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return url.getHost();
}
@Override
public int getPineconePort() {
URL url = null;
try {
url = URI.create(container.getEndpoint()).toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return url.getPort();
}
}
| TestInfraPineconeLocalContainer |
java | quarkusio__quarkus | extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/exporter/otlp/OTelExporterUtil.java | {
"start": 117,
"end": 557
} | class ____ {
private OTelExporterUtil() {
}
public static int getPort(URI uri) {
int originalPort = uri.getPort();
if (originalPort > -1) {
return originalPort;
}
if (isHttps(uri)) {
return 443;
}
return 80;
}
public static boolean isHttps(URI uri) {
return "https".equals(uri.getScheme().toLowerCase(Locale.ROOT));
}
}
| OTelExporterUtil |
java | junit-team__junit5 | junit-vintage-engine/src/test/java/org/junit/vintage/engine/discovery/VintageDiscovererTests.java | {
"start": 4817,
"end": 4943
} | class ____ {
@org.junit.Test
public void test() {
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
public static | Foo |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/support/GenericTypeAwareAutowireCandidateResolver.java | {
"start": 4196,
"end": 8023
} | class ____ applicable.
if (targetType == null && rbd != null && rbd.hasBeanClass() && rbd.getFactoryMethodName() == null) {
Class<?> beanClass = rbd.getBeanClass();
if (!FactoryBean.class.isAssignableFrom(beanClass)) {
targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanClass));
}
}
}
if (targetType == null) {
return true;
}
if (cacheType) {
rbd.targetType = targetType;
}
// Pre-declared target type: In case of a generic FactoryBean type,
// unwrap nested generic type when matching a non-FactoryBean type.
Class<?> targetClass = targetType.resolve();
if (targetClass != null && FactoryBean.class.isAssignableFrom(targetClass)) {
Class<?> classToMatch = dependencyType.resolve();
if (classToMatch != null && !FactoryBean.class.isAssignableFrom(classToMatch) &&
!classToMatch.isAssignableFrom(targetClass)) {
targetType = targetType.getGeneric();
if (descriptor.fallbackMatchAllowed()) {
// Matching the Class-based type determination for FactoryBean
// objects in the lazy-determination getType code path above.
targetType = ResolvableType.forClass(targetType.resolve());
}
}
}
if (descriptor.fallbackMatchAllowed()) {
// Fallback matches allow unresolvable generics, for example, plain HashMap to Map<String,String>;
// and pragmatically also java.util.Properties to any Map (since despite formally being a
// Map<Object,Object>, java.util.Properties is usually perceived as a Map<String,String>).
if (targetType.hasUnresolvableGenerics()) {
return dependencyType.isAssignableFromResolvedPart(targetType);
}
else if (targetType.resolve() == Properties.class) {
return true;
}
}
// Full check for complex generic type match...
return dependencyType.isAssignableFrom(targetType);
}
protected @Nullable RootBeanDefinition getResolvedDecoratedDefinition(RootBeanDefinition rbd) {
BeanDefinitionHolder decDef = rbd.getDecoratedDefinition();
if (decDef != null && this.beanFactory instanceof ConfigurableListableBeanFactory clbf) {
if (clbf.containsBeanDefinition(decDef.getBeanName())) {
BeanDefinition dbd = clbf.getMergedBeanDefinition(decDef.getBeanName());
if (dbd instanceof RootBeanDefinition rootBeanDef) {
return rootBeanDef;
}
}
}
return null;
}
protected @Nullable ResolvableType getReturnTypeForFactoryMethod(RootBeanDefinition rbd, DependencyDescriptor descriptor) {
// Should typically be set for any kind of factory method, since the BeanFactory
// pre-resolves them before reaching out to the AutowireCandidateResolver...
ResolvableType returnType = rbd.factoryMethodReturnType;
if (returnType == null) {
Method factoryMethod = rbd.getResolvedFactoryMethod();
if (factoryMethod != null) {
returnType = ResolvableType.forMethodReturnType(factoryMethod);
}
}
if (returnType != null) {
Class<?> resolvedClass = returnType.resolve();
if (resolvedClass != null && descriptor.getDependencyType().isAssignableFrom(resolvedClass)) {
// Only use factory method metadata if the return type is actually expressive enough
// for our dependency. Otherwise, the returned instance type may have matched instead
// in case of a singleton instance having been registered with the container already.
return returnType;
}
}
return null;
}
/**
* This implementation clones all instance fields through standard
* {@link Cloneable} support, allowing for subsequent reconfiguration
* of the cloned instance through a fresh {@link #setBeanFactory} call.
* @see #clone()
*/
@Override
public AutowireCandidateResolver cloneIfNecessary() {
try {
return (AutowireCandidateResolver) clone();
}
catch (CloneNotSupportedException ex) {
throw new IllegalStateException(ex);
}
}
}
| if |
java | quarkusio__quarkus | extensions/funqy/funqy-knative-events/deployment/src/test/java/io/quarkus/funqy/test/WithAttributeFilter.java | {
"start": 309,
"end": 2922
} | class ____ {
@Funq
@CloudEventMapping(attributes = { @EventAttribute(name = "source", value = "mytestvalue") })
public String listOfStrings(List<Identity> identityList) {
return identityList
.stream()
.map(Identity::getName)
.collect(Collectors.joining(":"));
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = { @EventAttribute(name = "source", value = "testvalue") })
public String toCommaSeparated(List<Identity> identityList) {
return identityList
.stream()
.map(Identity::getName)
.collect(Collectors.joining(","));
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = { @EventAttribute(name = "source", value = "test2") })
public String toSemicolonSeparated(List<Identity> identityList) {
return identityList
.stream()
.map(Identity::getName)
.collect(Collectors.joining(";"));
}
@Funq
@CloudEventMapping(trigger = "integer", attributes = { @EventAttribute(name = "source", value = "test"),
@EventAttribute(name = "custom", value = "hello") })
public Uni<List<Integer>> range(int n) {
return Uni.createFrom().item(() -> IntStream.range(0, n)
.boxed()
.collect(Collectors.toList()));
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = {
@EventAttribute(name = "source", value = "test"),
@EventAttribute(name = "custom", value = "value") })
public String foo(List<Identity> identityList) {
return "value";
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = {
@EventAttribute(name = "source", value = "test"),
@EventAttribute(name = "custom", value = "someOtherValue") })
public String bar(List<Identity> identityList) {
return "someOtherValue";
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = {
@EventAttribute(name = "source", value = "test"),
@EventAttribute(name = "customA", value = "value") })
public String anotherFoo(List<Identity> identityList) {
return "value";
}
@Funq
@CloudEventMapping(trigger = "listOfStrings", attributes = {
@EventAttribute(name = "source", value = "test"),
@EventAttribute(name = "customB", value = "value") })
public String anotherBar(List<Identity> identityList) {
return "someOtherValue";
}
}
| WithAttributeFilter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/refcursor/NumValue.java | {
"start": 663,
"end": 1750
} | class ____ implements Serializable {
@Id
@Column(name = "BOT_NUM", nullable = false)
private long num;
@Column(name = "BOT_VALUE")
private String value;
public NumValue() {
}
public NumValue(long num, String value) {
this.num = num;
this.value = value;
}
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof NumValue ) ) return false;
NumValue numValue = (NumValue) o;
if ( num != numValue.num ) return false;
if ( value != null ? !value.equals( numValue.value ) : numValue.value != null ) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) ( num ^ ( num >>> 32 ) );
result = 31 * result + ( value != null ? value.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "NumValue(num = " + num + ", value = " + value + ")";
}
public long getNum() {
return num;
}
public void setNum(long num) {
this.num = num;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| NumValue |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/RoutePredicateHandlerMappingEmptyPredicatesTests.java | {
"start": 1758,
"end": 2034
} | class ____ {
@Bean
RouteDefinitionLocator myRouteDefinitionLocator() {
RouteDefinition definition = new RouteDefinition();
definition.setId("empty_route");
definition.setUri(URI.create("https://example"));
return () -> Flux.just(definition);
}
}
}
| TestConfig |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_112_orderBy.java | {
"start": 987,
"end": 6424
} | class ____ extends TestCase {
public void test_0() throws Exception {
String sql = "select coach_id, tournament_name ,tournament_id, season_id, season, count(1) as num,\n" +
"sum(case when wdl = 0 then 1 else 0 end) as loss,\n" +
"sum(case when wdl = 1 then 1 else 0 end) as draw,\n" +
"sum(case when wdl = 3 then 1 else 0 end) as win\n" +
"from (\n" +
"select a.coach_id,b.team_id, a.home_team_id, a.away_team_id,a.tournament_id, a.tournament_name, a.season_id,a.season, a.result,\n" +
"case\n" +
"when b.team_id = a.home_team_id then (case\n" +
"WHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':',a.result)-1), SIGNED) > CONVERT(SUBSTRING(a.result, LOCATE(':',a.result)+1, CHAR_LENGTH(a.result)), SIGNED) THEN 3\n" +
"WHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':',a.result)-1), SIGNED) < CONVERT(SUBSTRING(a.result, LOCATE(':',a.result)+1, CHAR_LENGTH(a.result)), SIGNED) THEN 0\n" +
"else 1 end )\n" +
"when b.team_id = a.away_team_id then (case\n" +
"WHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':',a.result)-1), SIGNED) > CONVERT(SUBSTRING(a.result, LOCATE(':',a.result)+1, CHAR_LENGTH(a.result)), SIGNED) THEN 0\n" +
"WHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':',a.result)-1), SIGNED) < CONVERT(SUBSTRING(a.result, LOCATE(':',a.result)+1, CHAR_LENGTH(a.result)), SIGNED) THEN 3\n" +
"else 1 end ) end as wdl\n" +
"from p_coach_match_detail as a\n" +
"left join p_coach_career b on a.match_date > b.appoint_time and a.match_date < b.until_time and a.coach_id = b.coach_id and b.function = 'Manager'\n" +
") a where season_id >= 2017 and coach_id = 5075 group by coach_id, tournament_name ,tournament_id, season_id, season ORDER BY season_id DESC";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, DbType.mysql);
assertEquals(1, statementList.size());
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
// print(statementList);
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(2, visitor.getTables().size());
assertEquals(14, visitor.getColumns().size());
assertEquals(10, visitor.getConditions().size());
assertEquals(1, visitor.getOrderByColumns().size());
assertEquals("SELECT coach_id, tournament_name, tournament_id, season_id, season\n" +
"\t, count(1) AS num\n" +
"\t, sum(CASE\n" +
"\t\tWHEN wdl = 0 THEN 1\n" +
"\t\tELSE 0\n" +
"\tEND) AS loss\n" +
"\t, sum(CASE\n" +
"\t\tWHEN wdl = 1 THEN 1\n" +
"\t\tELSE 0\n" +
"\tEND) AS draw\n" +
"\t, sum(CASE\n" +
"\t\tWHEN wdl = 3 THEN 1\n" +
"\t\tELSE 0\n" +
"\tEND) AS win\n" +
"FROM (\n" +
"\tSELECT a.coach_id, b.team_id, a.home_team_id, a.away_team_id, a.tournament_id\n" +
"\t\t, a.tournament_name, a.season_id, a.season, a.result\n" +
"\t\t, CASE\n" +
"\t\t\tWHEN b.team_id = a.home_team_id THEN \n" +
"\t\t\t\t(CASE\n" +
"\t\t\t\t\tWHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':', a.result) - 1), SIGNED) > CONVERT(SUBSTRING(a.result, LOCATE(':', a.result) + 1, CHAR_LENGTH(a.result)), SIGNED) THEN 3\n" +
"\t\t\t\t\tWHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':', a.result) - 1), SIGNED) < CONVERT(SUBSTRING(a.result, LOCATE(':', a.result) + 1, CHAR_LENGTH(a.result)), SIGNED) THEN 0\n" +
"\t\t\t\t\tELSE 1\n" +
"\t\t\t\tEND)\n" +
"\t\t\tWHEN b.team_id = a.away_team_id THEN \n" +
"\t\t\t\t(CASE\n" +
"\t\t\t\t\tWHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':', a.result) - 1), SIGNED) > CONVERT(SUBSTRING(a.result, LOCATE(':', a.result) + 1, CHAR_LENGTH(a.result)), SIGNED) THEN 0\n" +
"\t\t\t\t\tWHEN CONVERT(SUBSTRING(a.result, 1, LOCATE(':', a.result) - 1), SIGNED) < CONVERT(SUBSTRING(a.result, LOCATE(':', a.result) + 1, CHAR_LENGTH(a.result)), SIGNED) THEN 3\n" +
"\t\t\t\t\tELSE 1\n" +
"\t\t\t\tEND)\n" +
"\t\tEND AS wdl\n" +
"\tFROM p_coach_match_detail a\n" +
"\t\tLEFT JOIN p_coach_career b\n" +
"\t\tON a.match_date > b.appoint_time\n" +
"\t\t\tAND a.match_date < b.until_time\n" +
"\t\t\tAND a.coach_id = b.coach_id\n" +
"\t\t\tAND b.function = 'Manager'\n" +
") a\n" +
"WHERE season_id >= 2017\n" +
"\tAND coach_id = 5075\n" +
"GROUP BY coach_id, tournament_name, tournament_id, season_id, season\n" +
"ORDER BY season_id DESC", stmt.toString());
}
}
| MySqlSelectTest_112_orderBy |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/core/token/TokenService.java | {
"start": 1738,
"end": 1866
} | interface ____
* be expanded to provide such capabilities directly.
* </p>
*
* @author Ben Alex
* @since 2.0.1
*
*/
public | to |
java | apache__camel | components/camel-wal/src/test/java/org/apache/camel/component/wal/LogTestBase.java | {
"start": 1173,
"end": 3365
} | class ____ {
protected static final long RECORD_COUNT = TimeUnit.HOURS.toSeconds(1);
private static final Logger LOG = LoggerFactory.getLogger(LogTestBase.class);
@TempDir
protected File testDir;
protected static LogEntry createNewLogEntry(List<Instant> values, int i) {
String keyData = "record-" + i;
ByteBuffer value = ByteBuffer.allocate(Long.BYTES);
Instant now = Instant.now();
value.putLong(now.toEpochMilli());
if (values != null) {
values.add(now);
}
LogEntry entry = new LogEntry(
LogEntry.EntryState.NEW, 0,
keyData.getBytes(), 0, value.array());
return entry;
}
protected List<Instant> generateDataFilePredictable(
Consumer<EntryInfo.CachedEntryInfo> offsetConsumer, LogWriter logWriter, long total)
throws IOException {
List<Instant> values = new ArrayList<>();
LOG.debug("Number of records to write: {}", total);
for (int i = 0; i < total; i++) {
LogEntry entry = createNewLogEntry(values, i);
final EntryInfo.CachedEntryInfo entryInfo = logWriter.append(entry);
if (offsetConsumer != null) {
offsetConsumer.accept(entryInfo);
}
}
return values;
}
protected List<Instant> generateDataFilePredictable(Consumer<EntryInfo.CachedEntryInfo> offsetConsumer, LogWriter logWriter)
throws IOException {
return generateDataFilePredictable(offsetConsumer, logWriter, RECORD_COUNT);
}
protected List<Instant> generateDataFilePredictable(Consumer<EntryInfo.CachedEntryInfo> offsetConsumer) throws IOException {
File reportFile = new File(testDir, "test.data");
final DefaultLogSupervisor scheduledFlushPolicy = new DefaultLogSupervisor(100);
try (LogWriter logWriter = new LogWriter(reportFile, scheduledFlushPolicy)) {
return generateDataFilePredictable(offsetConsumer, logWriter);
}
}
protected List<Instant> generateDataFilePredictable() throws IOException {
return generateDataFilePredictable(null);
}
}
| LogTestBase |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest26.java | {
"start": 1016,
"end": 2383
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE lookup" +
" (id INT, INDEX USING BTREE (id))" +
" MAX_ROWS 1024;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(1, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("lookup")));
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE lookup (" +
"\n\tid INT," +
"\n\tINDEX USING BTREE(id)" +
"\n) MAX_ROWS = 1024;", output);
}
}
| MySqlCreateTableTest26 |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/JsonValueSerializationTest.java | {
"start": 1127,
"end": 1361
} | class ____ check that it is also possible to
* force specific serializer to use with @JsonValue annotated
* method. Difference is between Integer serialization, and
* conversion to a Json String.
*/
final static | to |
java | spring-projects__spring-boot | module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/docker/compose/PostgresJdbcDockerComposeConnectionDetailsFactory.java | {
"start": 1475,
"end": 2032
} | class ____
extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> {
protected PostgresJdbcDockerComposeConnectionDetailsFactory() {
super("postgres");
}
@Override
protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new PostgresJdbcDockerComposeConnectionDetails(source.getRunningService(), source.getEnvironment());
}
/**
* {@link JdbcConnectionDetails} backed by a {@code postgres} {@link RunningService}.
*/
static | PostgresJdbcDockerComposeConnectionDetailsFactory |
java | apache__logging-log4j2 | log4j-api-test/src/test/java/org/apache/logging/log4j/util/Log4jCharsetsPropertiesTest.java | {
"start": 1095,
"end": 1903
} | class ____ {
/**
* Tests that we can load all mappings.
*/
@Test
void testLoadAll() {
final ResourceBundle resourceBundle = PropertiesUtil.getCharsetsResourceBundle();
final Enumeration<String> keys = resourceBundle.getKeys();
while (keys.hasMoreElements()) {
final String key = keys.nextElement();
assertFalse(
Charset.isSupported(key),
String.format("The Charset %s is available and should not be mapped", key));
final String value = resourceBundle.getString(key);
assertTrue(
Charset.isSupported(value),
String.format("The Charset %s is not available and is mapped from %s", value, key));
}
}
}
| Log4jCharsetsPropertiesTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java | {
"start": 6232,
"end": 7813
} | class ____ implements IndexedSortable {
private int[] valindex;
private int[] valindirect;
private int[] values;
private final long seed;
public SampleSortable() {
this(50);
}
public SampleSortable(int j) {
Random r = new Random();
seed = r.nextLong();
r.setSeed(seed);
values = new int[j];
valindex = new int[j];
valindirect = new int[j];
for (int i = 0; i < j; ++i) {
valindex[i] = valindirect[i] = i;
values[i] = r.nextInt(1000);
}
}
public SampleSortable(int[] values) {
this.values = values;
valindex = new int[values.length];
valindirect = new int[values.length];
for (int i = 0; i < values.length; ++i) {
valindex[i] = valindirect[i] = i;
}
seed = 0;
}
public long getSeed() {
return seed;
}
@Override
public int compare(int i, int j) {
// assume positive
return
values[valindirect[valindex[i]]] - values[valindirect[valindex[j]]];
}
@Override
public void swap(int i, int j) {
int tmp = valindex[i];
valindex[i] = valindex[j];
valindex[j] = tmp;
}
public int[] getSorted() {
int[] ret = new int[values.length];
for (int i = 0; i < ret.length; ++i) {
ret[i] = values[valindirect[valindex[i]]];
}
return ret;
}
public int[] getValues() {
int[] ret = new int[values.length];
System.arraycopy(values, 0, ret, 0, values.length);
return ret;
}
}
public static | SampleSortable |
java | apache__camel | components/camel-sjms/src/test/java/org/apache/camel/component/sjms/consumer/InOutConsumerTempQueueAsyncTest.java | {
"start": 1169,
"end": 2899
} | class ____ extends JmsTestSupport {
@Test
public void testAsync() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Hello Camel");
template.sendBody("sjms:start.queue.InOutConsumerTempQueueAsyncTest", "Hello Camel");
template.sendBody("sjms:start.queue.InOutConsumerTempQueueAsyncTest", "Hello World");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("sjms:queue:start.queue.InOutConsumerTempQueueAsyncTest?asyncConsumer=true")
.log("Requesting ${body} with thread ${threadName}")
.to(ExchangePattern.InOut,
"sjms:queue:in.out.temp.queue.InOutConsumerTempQueueAsyncTest?replyToConcurrentConsumers=2")
.log("Result ${body} with thread ${threadName}")
.to("mock:result");
from("sjms:queue:in.out.temp.queue.InOutConsumerTempQueueAsyncTest?concurrentConsumers=2").to("log:before")
.log("Replying ${body} with thread ${threadName}")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
String body = (String) exchange.getIn().getBody();
if (body.contains("Camel")) {
Thread.sleep(2000);
}
}
});
}
};
}
}
| InOutConsumerTempQueueAsyncTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java | {
"start": 27637,
"end": 27917
} | class ____ be different than the final output
* value class.
*
* @param theClass the map output key class.
*/
public void setMapOutputKeyClass(Class<?> theClass) {
setClass(JobContext.MAP_OUTPUT_KEY_CLASS, theClass, Object.class);
}
/**
* Get the value | to |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/BundleDeserializationCastTest.java | {
"start": 8335,
"end": 9074
} | class ____ {
void test() {
Bundle bundle = new Bundle();
// BUG: Diagnostic matches: X
CustomCharSequence[] cs = (CustomCharSequence[]) bundle.getSerializable("key");
}
}
""")
.expectErrorMessage(
"X",
Predicates.and(
Predicates.containsPattern("CustomCharSequence\\[\\] may be transformed"),
Predicates.containsPattern("cast to CharSequence\\[\\]")))
.doTest();
}
@Test
public void negativeCaseGetStringArray() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import android.os.Bundle;
public | Test |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/WhereRestrictable.java | {
"start": 496,
"end": 874
} | interface ____ {
/**
* Does this restrictable have a where restriction?
*/
boolean hasWhereRestrictions();
/**
* Apply the {@link org.hibernate.annotations.SQLRestriction} restrictions
*/
void applyWhereRestrictions(
Consumer<Predicate> predicateConsumer,
TableGroup tableGroup,
boolean useQualifier,
SqlAstCreationState creationState);
}
| WhereRestrictable |
java | apache__flink | flink-core/src/main/java/org/apache/flink/configuration/JobManagerOptions.java | {
"start": 45108,
"end": 47955
} | enum ____ {
ALL_PRODUCERS_FINISHED(true),
ONLY_FINISHED_PRODUCERS(true),
UNFINISHED_PRODUCERS(false);
private final boolean onlyConsumeFinishedPartition;
HybridPartitionDataConsumeConstraint(boolean onlyConsumeFinishedPartition) {
this.onlyConsumeFinishedPartition = onlyConsumeFinishedPartition;
}
public boolean isOnlyConsumeFinishedPartition() {
return onlyConsumeFinishedPartition;
}
}
@Documentation.Section({
Documentation.Sections.EXPERT_SCHEDULING,
Documentation.Sections.ALL_JOB_MANAGER
})
public static final ConfigOption<HybridPartitionDataConsumeConstraint>
HYBRID_PARTITION_DATA_CONSUME_CONSTRAINT =
key("jobmanager.partition.hybrid.partition-data-consume-constraint")
.enumType(HybridPartitionDataConsumeConstraint.class)
.noDefaultValue()
.withDescription(
Description.builder()
.text(
"Controls the constraint that hybrid partition data can be consumed. "
+ "Note that this option is allowed only when %s has been set to %s. "
+ "Accepted values are:",
code(SCHEDULER.key()),
code(SchedulerType.AdaptiveBatch.name()))
.list(
text(
"'%s': hybrid partition data can be consumed only when all producers are finished.",
code(ALL_PRODUCERS_FINISHED.name())),
text(
"'%s': hybrid partition data can be consumed when its producer is finished.",
code(ONLY_FINISHED_PRODUCERS.name())),
text(
"'%s': hybrid partition data can be consumed even if its producer is un-finished.",
code(UNFINISHED_PRODUCERS.name())))
.build());
// ---------------------------------------------------------------------------------------------
private JobManagerOptions() {
throw new IllegalAccessError();
}
}
| HybridPartitionDataConsumeConstraint |
java | alibaba__nacos | auth/src/main/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilder.java | {
"start": 1185,
"end": 2582
} | class ____ implements IdentityContextBuilder<Request> {
private final NacosAuthConfig authConfig;
public GrpcIdentityContextBuilder(NacosAuthConfig authConfig) {
this.authConfig = authConfig;
}
/**
* get identity context from grpc.
*
* @param request grpc request
* @return IdentityContext request context
*/
@Override
public IdentityContext build(Request request) {
Optional<AuthPluginService> authPluginService = AuthPluginManager.getInstance()
.findAuthServiceSpiImpl(authConfig.getNacosAuthSystemType());
IdentityContext result = new IdentityContext();
getRemoteIp(request, result);
if (!authPluginService.isPresent()) {
return result;
}
Set<String> identityNames = new HashSet<>(authPluginService.get().identityNames());
Map<String, String> map = request.getHeaders();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (identityNames.contains(entry.getKey())) {
result.setParameter(entry.getKey(), entry.getValue());
}
}
return result;
}
private void getRemoteIp(Request request, IdentityContext result) {
result.setParameter(Constants.Identity.REMOTE_IP, request.getHeader(Constants.Identity.X_REAL_IP));
}
}
| GrpcIdentityContextBuilder |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Trees.java | {
"start": 974,
"end": 1967
} | class ____ extends ReflectionWrapper {
private Trees(Object instance) {
super("com.sun.source.util.Trees", instance);
}
Tree getTree(Element element) throws Exception {
Object tree = findMethod("getTree", Element.class).invoke(getInstance(), element);
return (tree != null) ? new Tree(tree) : null;
}
static Trees instance(ProcessingEnvironment env) throws Exception {
try {
ClassLoader classLoader = env.getClass().getClassLoader();
Class<?> type = findClass(classLoader, "com.sun.source.util.Trees");
Method method = findMethod(type, "instance", ProcessingEnvironment.class);
return new Trees(method.invoke(null, env));
}
catch (Exception ex) {
return instance(unwrap(env));
}
}
private static ProcessingEnvironment unwrap(ProcessingEnvironment wrapper) throws Exception {
Field delegateField = wrapper.getClass().getDeclaredField("delegate");
delegateField.setAccessible(true);
return (ProcessingEnvironment) delegateField.get(wrapper);
}
}
| Trees |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableThrottleFirstTimed.java | {
"start": 1993,
"end": 4382
} | class ____<T>
extends AtomicReference<Disposable>
implements Observer<T>, Disposable, Runnable {
private static final long serialVersionUID = 786994795061867455L;
final Observer<? super T> downstream;
final long timeout;
final TimeUnit unit;
final Scheduler.Worker worker;
final Consumer<? super T> onDropped;
Disposable upstream;
volatile boolean gate;
DebounceTimedObserver(
Observer<? super T> actual,
long timeout,
TimeUnit unit,
Worker worker,
Consumer<? super T> onDropped) {
this.downstream = actual;
this.timeout = timeout;
this.unit = unit;
this.worker = worker;
this.onDropped = onDropped;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (!gate) {
gate = true;
downstream.onNext(t);
Disposable d = get();
if (d != null) {
d.dispose();
}
DisposableHelper.replace(this, worker.schedule(this, timeout, unit));
} else if (onDropped != null) {
try {
onDropped.accept(t);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
upstream.dispose();
downstream.onError(ex);
worker.dispose();
}
}
}
@Override
public void run() {
gate = false;
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
worker.dispose();
}
@Override
public void onComplete() {
downstream.onComplete();
worker.dispose();
}
@Override
public void dispose() {
upstream.dispose();
worker.dispose();
}
@Override
public boolean isDisposed() {
return worker.isDisposed();
}
}
}
| DebounceTimedObserver |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/testutils/statemigration/TestType.java | {
"start": 2867,
"end": 3769
} | class ____ extends TestTypeSerializerBase {
private static final long serialVersionUID = 5053346160938769779L;
@Override
public void serialize(TestType record, DataOutputView target) throws IOException {
target.writeUTF(record.getKey());
target.writeInt(record.getValue());
}
@Override
public TestType deserialize(DataInputView source) throws IOException {
return new TestType(source.readUTF(), source.readInt());
}
@Override
public TypeSerializerSnapshot<TestType> snapshotConfiguration() {
return new V1TestTypeSerializerSnapshot();
}
}
/**
* A serializer that read / writes {@link TestType} in schema version 2. Migration is required
* if the state was previously written with {@link V1TestTypeSerializer}.
*/
public static | V1TestTypeSerializer |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToGeohashTests.java | {
"start": 1081,
"end": 2512
} | class ____ extends AbstractScalarFunctionTestCase {
public ToGeohashTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
this.testCase = testCaseSupplier.get();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
final String attribute = "Attribute[channel=0]";
final String evaluator = "ToGeohashFromStringEvaluator[in=Attribute[channel=0]]";
final List<TestCaseSupplier> suppliers = new ArrayList<>();
TestCaseSupplier.forUnaryGeoGrid(suppliers, attribute, DataType.GEOHASH, DataType.GEOHASH, v -> v, List.of());
TestCaseSupplier.forUnaryGeoGrid(suppliers, attribute, DataType.LONG, DataType.GEOHASH, v -> v, List.of());
TestCaseSupplier.forUnaryGeoGrid(suppliers, evaluator, DataType.KEYWORD, DataType.GEOHASH, ToGeohashTests::valueOf, List.of());
TestCaseSupplier.forUnaryGeoGrid(suppliers, evaluator, DataType.TEXT, DataType.GEOHASH, ToGeohashTests::valueOf, List.of());
return parameterSuppliersFromTypedDataWithDefaultChecks(true, suppliers);
}
private static long valueOf(Object gridAddress) {
assert gridAddress instanceof BytesRef;
return Geohash.longEncode(((BytesRef) gridAddress).utf8ToString());
}
@Override
protected Expression build(Source source, List<Expression> args) {
return new ToGeohash(source, args.get(0));
}
}
| ToGeohashTests |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/cli/plugin/PluginUtil.java | {
"start": 532,
"end": 8261
} | class ____ {
private PluginUtil() {
//Utility
}
public static boolean shouldSync(Path projectRoot, PluginCatalog catalog) {
return shouldSync(Optional.ofNullable(projectRoot), catalog);
}
public static boolean shouldSync(Optional<Path> projectRoot, PluginCatalog catalog) {
LocalDateTime catalogTime = catalog.getLastUpdateDate();
LocalDateTime lastBuildFileModifiedTime = getLastBuildFileModifiedTime(projectRoot);
return catalogTime.isBefore(lastBuildFileModifiedTime) || LocalDateTime.now().minusDays(7).isAfter(catalogTime);
}
/**
* Get the {@link PluginType} that corresponds the the specified location.
*
* @param the location
* @return the {@link PluginType} that corresponds to the location.
*/
public static PluginType getType(String location) {
Optional<URL> url = checkUrl(location);
Optional<Path> path = checkPath(location);
Optional<GACTV> gactv = checkGACTV(location);
return getType(gactv, url, path);
}
/**
* Get the {@link PluginType} that corresponds the the specified locations.
*
* @param url the url
* @param path the path
* @param gactv the gactv
* @return the {@link PluginType} that corresponds to the location.
*/
public static PluginType getType(Optional<GACTV> gactv, Optional<URL> url, Optional<Path> path) {
return gactv.map(i -> PluginType.maven)
.or(() -> url.map(u -> u.getPath()).or(() -> path.map(Path::toAbsolutePath).map(Path::toString))
.filter(f -> f.endsWith(".jar") || f.endsWith(".java")) // java or jar files
.map(f -> f.substring(f.lastIndexOf(".") + 1)) // get extension
.map(PluginType::valueOf)) // map to type
.or(() -> path.filter(p -> p.toFile().exists()).map(i -> PluginType.executable))
.orElse(PluginType.jbang);
}
/**
* Check if the plugin can be found.
* The method is used to determined the plugin can be located.
*
* @return true if path is not null and points to an existing file.
*/
public static boolean shouldRemove(Plugin p) {
if (p == null) {
return true;
}
if (!p.getLocation().isPresent()) {
return true;
}
if (p.getType() == PluginType.executable) {
return !checkPath(p.getLocation()).map(Path::toFile).map(File::exists).orElse(false);
}
if (checkUrl(p.getLocation()).isPresent()) { //We don't want to remove remotely located plugins
return false;
}
if (checkGACTV(p.getLocation()).isPresent() && p.getType() != PluginType.extension) { //We don't want to remove remotely located plugins
return false;
}
if (p.getLocation().map(PluginUtil::isLocalFile).orElse(false)) {
return false;
}
return true;
}
/**
* Chekcs if specified {@link String} is a valid {@URL}.
*
* @param location The string to check
* @return The {@link URL} wrapped in {@link Optional} if valid, empty otherwise.
*/
public static Optional<URL> checkUrl(String location) {
try {
return Optional.of(new URL(location));
} catch (MalformedURLException | NullPointerException e) {
return Optional.empty();
}
}
public static Optional<URL> checkUrl(Optional<String> location) {
return location.flatMap(PluginUtil::checkUrl);
}
/**
* Chekcs if specified {@link String} is a valid {@URL}.
*
* @param location The string to check
* @return The {@link URL} wrapped in {@link Optional} if valid, empty otherwise.
*/
public static Optional<GACTV> checkGACTV(String location) {
try {
return Optional.of(GACTV.fromString(location));
} catch (IllegalArgumentException | NullPointerException e) {
return Optional.empty();
}
}
public static Optional<GACTV> checkGACTV(Optional<String> location) {
return location.flatMap(PluginUtil::checkGACTV);
}
/**
* Chekcs if specified {@link String} is a valid path.
*
* @param location The string to check
* @return The {@link Path} wrapped in {@link Optional} if valid, empty otherwise.
*/
public static Optional<Path> checkPath(String location) {
try {
return Optional.of(Paths.get(location));
} catch (InvalidPathException | NullPointerException e) {
return Optional.empty();
}
}
public static Optional<Path> checkPath(Optional<String> location) {
return location.flatMap(PluginUtil::checkPath);
}
/**
* Chekcs if specified {@link String} contains a valid remote catalog
*
* @param location The string to check
* @return The catalog wrapped in {@link Optional} if valid, empty otherwise.
*/
public static Optional<String> checkRemoteCatalog(String location) {
return Optional.ofNullable(location)
.filter(l -> l.contains("@"))
.map(l -> l.substring(l.lastIndexOf("@") + 1))
.filter(l -> !l.isEmpty());
}
public static Optional<String> checkRemoteCatalog(Optional<String> location) {
return location.flatMap(PluginUtil::checkRemoteCatalog);
}
/**
* Checks if location is remote.
*
* @param location the specifiied location.
* @return true if location is url or gactv
*/
public static boolean isRemoteLocation(String location) {
return checkUrl(location).isPresent() || checkGACTV(location).isPresent() || checkRemoteCatalog(location).isPresent();
}
/**
* Checks if location is a file that does exists locally.
*
* @param location the specifiied location.
* @return true if location is url or gactv
*/
public static boolean isLocalFile(String location) {
return checkPath(location).map(p -> p.toFile().exists()).orElse(false);
}
/**
* Checks if location is a file that does exists under the project root.
*
* @param projectRoot the root of the project.
* @param location the specifiied location.
* @return true if location is url or gactv
*/
public static boolean isProjectFile(Path projectRoot, String location) {
return checkPath(location)
.map(Path::normalize)
.map(Path::toFile)
.filter(f -> f.getAbsolutePath().startsWith(projectRoot.normalize().toAbsolutePath().toString()))
.map(File::exists)
.orElse(false);
}
private static List<Path> getBuildFiles(Optional<Path> projectRoot) {
List<Path> buildFiles = new ArrayList<>();
if (projectRoot == null) {
return buildFiles;
}
projectRoot.ifPresent(root -> {
BuildTool buildTool = QuarkusProjectHelper.detectExistingBuildTool(root);
if (buildTool != null) {
for (String buildFile : buildTool.getBuildFiles()) {
buildFiles.add(root.resolve(buildFile));
}
}
});
return buildFiles;
}
private static LocalDateTime getLastBuildFileModifiedTime(Optional<Path> projectRoot) {
long lastModifiedMillis = getBuildFiles(projectRoot).stream().map(Path::toFile).filter(File::exists)
.map(File::lastModified)
.max(Long::compare).orElse(0L);
return Instant.ofEpochMilli(lastModifiedMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
| PluginUtil |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/OrderByEmbeddableX2Test.java | {
"start": 3370,
"end": 3632
} | class ____ {
@Embedded
private Contained contained;
public Embed() {
}
public Contained getContained() {
return contained;
}
public void setContained(Contained contained) {
this.contained = contained;
}
}
@Embeddable
public static | Embed |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/FakePlugin.java | {
"start": 2010,
"end": 2545
} | class ____ {}
@PluginFactory
public static FakePlugin newPlugin(
@PluginAttribute("attribute") int attribute,
@PluginElement("layout") Layout<? extends Serializable> layout,
@PluginConfiguration Configuration config,
@PluginNode Node node,
@PluginLoggerContext LoggerContext loggerContext,
@PluginValue("value") String value) {
return null;
}
public static Builder newBuilder() {
return new Builder();
}
public static | Nested |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/http2/Http2RSTFloodProtectionTest.java | {
"start": 1394,
"end": 4113
} | class ____ {
private static final String configuration = """
quarkus.http.ssl.certificate.key-store-file=server-keystore.jks
quarkus.http.ssl.certificate.key-store-password=secret
""";
@TestHTTPResource(value = "/ping", ssl = true)
URL sslUrl;
@TestHTTPResource(value = "/ping")
URL url;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyBean.class)
.addAsResource(new StringAsset(configuration), "application.properties")
.addAsResource(new File("target/certs/ssl-test-keystore.jks"), "server-keystore.jks"));
@Test
void testRstFloodProtectionWithTlsEnabled() throws Exception {
HttpClientOptions options = new HttpClientOptions()
.setUseAlpn(true)
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setTrustOptions(new JksOptions().setPath(new File("target/certs/ssl-test-truststore.jks").getAbsolutePath())
.setPassword("secret"));
var client = VertxCoreRecorder.getVertx().get().createHttpClient(options);
int port = sslUrl.getPort();
run(client, port, false);
}
@Test
public void testRstFloodProtection() throws InterruptedException {
HttpClientOptions options = new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(true);
var client = VertxCoreRecorder.getVertx().get().createHttpClient(options);
run(client, url.getPort(), true);
}
void run(HttpClient client, int port, boolean plain) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
client.connectionHandler(conn -> conn.goAwayHandler(ga -> {
Assertions.assertEquals(11, ga.getErrorCode());
latch.countDown();
}));
if (plain) {
// Emit a first request to establish a connection.
// It's HTTP/1 so, does not count in the number of requests.
client.request(GET, port, "localhost", "/ping")
.compose(HttpClientRequest::send);
}
for (int i = 0; i < 250; i++) { // must be higher than the Netty limit (200 / 30s)
client.request(GET, port, "localhost", "/ping")
.onSuccess(req -> req.end().onComplete(v -> req.reset()));
}
if (!latch.await(10, TimeUnit.SECONDS)) {
fail("RST flood protection failed");
}
}
@ApplicationScoped
public static | Http2RSTFloodProtectionTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/Deriv.java | {
"start": 1838,
"end": 4905
} | class ____ extends TimeSeriesAggregateFunction implements ToAggregator, TimestampAware {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Deriv", Deriv::new);
private final Expression timestamp;
@FunctionInfo(
type = FunctionType.TIME_SERIES_AGGREGATE,
returnType = { "double" },
description = "Calculates the derivative over time of a numeric field using linear regression.",
examples = { @Example(file = "k8s-timeseries", tag = "deriv") }
)
public Deriv(Source source, @Param(name = "field", type = { "long", "integer", "double" }) Expression field, Expression timestamp) {
this(source, field, Literal.TRUE, NO_WINDOW, timestamp);
}
public Deriv(Source source, Expression field, Expression filter, Expression window, Expression timestamp) {
super(source, field, filter, window, List.of(timestamp));
this.timestamp = timestamp;
}
private Deriv(org.elasticsearch.common.io.stream.StreamInput in) throws java.io.IOException {
this(
Source.readFrom((PlanStreamInput) in),
in.readNamedWriteable(Expression.class),
in.readNamedWriteable(Expression.class),
in.readNamedWriteable(Expression.class),
in.readNamedWriteableCollectionAsList(Expression.class).getFirst()
);
}
@Override
public Expression timestamp() {
return timestamp;
}
@Override
public AggregateFunction perTimeSeriesAggregation() {
return this;
}
@Override
public AggregateFunction withFilter(Expression filter) {
return new Deriv(source(), field(), filter, window(), timestamp);
}
@Override
public DataType dataType() {
return DataType.DOUBLE;
}
@Override
public TypeResolution resolveType() {
return TypeResolutions.isType(
field(),
dt -> dt.isNumeric() && dt != AGGREGATE_METRIC_DOUBLE,
sourceText(),
DEFAULT,
"numeric except counter types"
);
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new Deriv(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2), newChildren.get(3));
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, Deriv::new, field(), filter(), window(), timestamp);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
public AggregatorFunctionSupplier supplier() {
final DataType type = field().dataType();
return switch (type) {
case DOUBLE -> new DerivDoubleAggregatorFunctionSupplier();
case LONG -> new DerivLongAggregatorFunctionSupplier();
case INTEGER -> new DerivIntAggregatorFunctionSupplier();
default -> throw new IllegalArgumentException("Unsupported data type for deriv aggregation: " + type);
};
}
}
| Deriv |
java | elastic__elasticsearch | modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/PersianStemTokenFilterFactory.java | {
"start": 831,
"end": 1185
} | class ____ extends AbstractTokenFilterFactory {
PersianStemTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(name);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new PersianStemFilter(tokenStream);
}
}
| PersianStemTokenFilterFactory |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestSpeculativeExecOnCluster.java | {
"start": 11209,
"end": 11989
} | class ____ implements SleepDurationCalculator {
private double threshold = 1.0;
private double slowFactor = 1.0;
SleepDurationCalcImpl() {
}
public long calcSleepDuration(TaskAttemptID taId, int currCount,
int totalCount, long defaultSleepDuration) {
if (threshold <= ((double) currCount) / totalCount) {
return (long) (slowFactor * defaultSleepDuration);
}
return defaultSleepDuration;
}
}
/**
* The first attempt of task_0 slows down by a small factor that should not
* trigger a speculation. An speculated attempt should never beat the
* original task.
* A conservative estimator/speculator will speculate another attempt
* because of the slower progress.
*/
public static | SleepDurationCalcImpl |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/MyPrefixBean.java | {
"start": 852,
"end": 1121
} | class ____ {
private String prefix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String hello(String s) {
return prefix + " " + s;
}
}
| MyPrefixBean |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestAfsCheckPath.java | {
"start": 2555,
"end": 5377
} | class ____ extends AbstractFileSystem {
public DummyFileSystem(URI uri) throws URISyntaxException {
super(uri, "dummy", true, DEFAULT_PORT);
}
@Override
public int getUriDefaultPort() {
return DEFAULT_PORT;
}
@Override
public FSDataOutputStream createInternal(Path f, EnumSet<CreateFlag> flag,
FsPermission absolutePermission, int bufferSize, short replication,
long blockSize, Progressable progress, ChecksumOpt checksumOpt,
boolean createParent) throws IOException {
// deliberately empty
return null;
}
@Override
public boolean delete(Path f, boolean recursive)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
// deliberately empty
return false;
}
@Override
public BlockLocation[] getFileBlockLocations(Path f, long start, long len)
throws IOException {
// deliberately empty
return null;
}
@Override
public FileChecksum getFileChecksum(Path f) throws IOException {
// deliberately empty
return null;
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
// deliberately empty
return null;
}
@Override
public FsStatus getFsStatus() throws IOException {
// deliberately empty
return null;
}
@Override
@Deprecated
public FsServerDefaults getServerDefaults() throws IOException {
// deliberately empty
return null;
}
@Override
public FileStatus[] listStatus(Path f) throws IOException {
// deliberately empty
return null;
}
@Override
public void mkdir(Path dir, FsPermission permission, boolean createParent)
throws IOException {
// deliberately empty
}
@Override
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
// deliberately empty
return null;
}
@Override
public void renameInternal(Path src, Path dst) throws IOException {
// deliberately empty
}
@Override
public void setOwner(Path f, String username, String groupname)
throws IOException {
// deliberately empty
}
@Override
public void setPermission(Path f, FsPermission permission)
throws IOException {
// deliberately empty
}
@Override
public boolean setReplication(Path f, short replication) throws IOException {
// deliberately empty
return false;
}
@Override
public void setTimes(Path f, long mtime, long atime) throws IOException {
// deliberately empty
}
@Override
public void setVerifyChecksum(boolean verifyChecksum) throws IOException {
// deliberately empty
}
}
}
| DummyFileSystem |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ClassNamedLikeTypeParameterTest.java | {
"start": 1522,
"end": 1735
} | class ____ {}
}
""")
.doTest();
}
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"Test.java",
"""
public | X |
java | quarkusio__quarkus | integration-tests/opentelemetry-reactive/src/test/java/io/quarkus/it/opentelemetry/reactive/Utils.java | {
"start": 403,
"end": 1742
} | class ____ {
private Utils() {
}
public static List<Map<String, Object>> getSpans() {
return when().get("/export").body().as(new TypeRef<>() {
});
}
public static Map<String, Object> getSpanEventAttrs(String spanName, String eventName) {
return given()
.queryParam("spanName", spanName)
.queryParam("eventName", eventName)
.get("/export-event-attributes").body().as(new TypeRef<>() {
});
}
public static List<String> getExceptionEventData() {
return when().get("/exportExceptionMessages").body().as(new TypeRef<>() {
});
}
public static Map<String, Object> getSpanByKindAndParentId(List<Map<String, Object>> spans, SpanKind kind,
Object parentSpanId) {
List<Map<String, Object>> span = getSpansByKindAndParentId(spans, kind, parentSpanId);
assertEquals(1, span.size());
return span.get(0);
}
public static List<Map<String, Object>> getSpansByKindAndParentId(List<Map<String, Object>> spans, SpanKind kind,
Object parentSpanId) {
return spans.stream()
.filter(map -> map.get("kind").equals(kind.toString()))
.filter(map -> map.get("parentSpanId").equals(parentSpanId)).collect(toList());
}
}
| Utils |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/proxy/ProxyConfiguration.java | {
"start": 1762,
"end": 2340
} | interface ____ {
/**
* Intercepts a method call to a proxy.
*
* @param instance The proxied instance.
* @param method The invoked method.
* @param arguments The intercepted method arguments.
*
* @return The method's return value.
*
* @throws Throwable If the intercepted method raises an exception.
*/
@RuntimeType
Object intercept(@This Object instance, @Origin Method method, @AllArguments Object[] arguments) throws Throwable;
}
/**
* A static interceptor that guards against method calls before the interceptor is set.
*/
| Interceptor |
java | apache__flink | flink-core/src/main/java/org/apache/flink/util/function/FunctionUtils.java | {
"start": 1092,
"end": 1199
} | class ____ {
private FunctionUtils() {
throw new UnsupportedOperationException("This | FunctionUtils |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_127_for_qiuyan81.java | {
"start": 177,
"end": 3107
} | class ____ extends TestCase {
public void test_parserUndefined() {
String jsonString = "{PayStatus:0,RunEmpId:undefined}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_space() {
String jsonString = "{PayStatus:0,RunEmpId:undefined }";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_comma() {
String jsonString = "{PayStatus:0,RunEmpId:undefined,ext:1001}";
JSONObject json = (JSONObject) JSON.parse(jsonString);
Assert.assertEquals(1001, json.get("ext"));
Assert.assertEquals(0, json.get("PayStatus"));
Assert.assertEquals(3, json.size());
}
public void test_parserUndefined_array() {
String jsonString = "[0,undefined]";
Object json = JSON.parse(jsonString);
Assert.assertEquals("[0,null]", json.toString());
}
public void test_parserUndefined_n() {
String jsonString = "{PayStatus:0,RunEmpId:undefined\n}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_r() {
String jsonString = "{PayStatus:0,RunEmpId:undefined\r}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_t() {
String jsonString = "{PayStatus:0,RunEmpId:undefined\t}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_f() {
String jsonString = "{PayStatus:0,RunEmpId:undefined\f}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_b() {
String jsonString = "{PayStatus:0,RunEmpId:undefined\b}";
Object json = JSON.parse(jsonString);
Assert.assertEquals("{\"PayStatus\":0}", json.toString());
}
public void test_parserUndefined_single() {
String jsonString = "undefined";
Object json = JSON.parse(jsonString);
Assert.assertNull(json);
}
public void test_parserUndefined_field() {
String jsonString = "{undefined:1001}";
Object json = JSON.parse(jsonString);
Assert.assertEquals(1001, ((JSONObject)json).get("undefined"));
}
public void test_parserError() {
Exception error = null;
try {
String jsonString = "{PayStatus:0,RunEmpId:undefinedaa}";
JSON.parse(jsonString);
} catch (Exception ex) {
error = ex;
}
Assert.assertNotNull(error);
}
}
| Bug_127_for_qiuyan81 |
java | apache__dubbo | dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java | {
"start": 1776,
"end": 3139
} | interface ____
*/
@Deprecated
boolean generic() default false;
boolean injvm() default true;
boolean check() default true;
boolean init() default true;
boolean lazy() default false;
boolean stubevent() default false;
String reconnect() default "";
boolean sticky() default false;
String proxy() default "";
String stub() default "";
String cluster() default "";
int connections() default -1;
int callbacks() default -1;
String onconnect() default "";
String ondisconnect() default "";
String owner() default "";
String layer() default "";
int retries() default -1;
String loadbalance() default "";
boolean async() default false;
int actives() default -1;
boolean sent() default false;
String mock() default "";
String validation() default "";
int timeout() default -1;
String cache() default "";
String[] filter() default {};
String[] listener() default {};
String[] parameters() default {};
/**
* Application associated name
* @deprecated Do not set it and use the global Application Config
*/
@Deprecated
String application() default "";
String module() default "";
String consumer() default "";
String monitor() default "";
String[] registry() default {};
}
| class |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/DFSAdmin.java | {
"start": 5885,
"end": 7298
} | class ____ extends DFSAdminCommand {
private static final String NAME = "clrQuota";
private static final String USAGE = "-"+NAME+" <dirname>...<dirname>";
private static final String DESCRIPTION = USAGE + ": " +
"Clear the quota for each directory <dirName>.\n" +
"\t\tFor each directory, attempt to clear the quota. An error will be reported if\n" +
"\t\t1. the directory does not exist or is a file, or\n" +
"\t\t2. user is not an administrator.\n" +
"\t\tIt does not fault if the directory has no quota.";
/** Constructor */
ClearQuotaCommand(String[] args, int pos, Configuration conf) {
super(conf);
CommandFormat c = new CommandFormat(1, Integer.MAX_VALUE);
List<String> parameters = c.parse(args, pos);
this.args = parameters.toArray(new String[parameters.size()]);
}
/** Check if a command is the clrQuota command
*
* @param cmd A string representation of a command starting with "-"
* @return true if this is a clrQuota command; false otherwise
*/
public static boolean matches(String cmd) {
return ("-"+NAME).equals(cmd);
}
@Override
public String getCommandName() {
return NAME;
}
@Override
public void run(Path path) throws IOException {
dfs.setQuota(path, HdfsConstants.QUOTA_RESET, HdfsConstants.QUOTA_DONT_SET);
}
}
/** A | ClearQuotaCommand |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/constructornoinject/NoArgConstructorTakesPrecedenceTest.java | {
"start": 330,
"end": 656
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(CombineHarvester.class);
@Test
public void testInjection() {
assertEquals("OK", Arc.container().instance(CombineHarvester.class).get().getHead());
}
@Singleton
static | NoArgConstructorTakesPrecedenceTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/registerclientheaders/HeaderSettingClient.java | {
"start": 458,
"end": 781
} | interface ____ {
String HEADER = "my-header";
@Path("/with-incoming-header")
@GET
RequestData setHeaderValue(@HeaderParam(HEADER) String headerName);
@Path("/with-incoming-header/no-passing")
@GET
RequestData setHeaderValueNoPassing(@HeaderParam(HEADER) String headerName);
}
| HeaderSettingClient |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.