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
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest10.java
|
{
"start": 239,
"end": 867
}
|
class ____ extends TestCase {
protected void setUp() throws Exception {
JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
JSON.defaultLocale = Locale.CHINA;
}
public void test_date() throws Exception {
String text = "{\"value\":\"1979-07-14\"}";
VO vo = JSON.parseObject(text, VO.class);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale);
dateFormat.setTimeZone(JSON.defaultTimeZone);
Assert.assertEquals(vo.getValue(), dateFormat.parse("1979-07-14").getTime());
}
public static
|
DateParseTest10
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/http/impl/http1x/VertxAssembledHttpResponse.java
|
{
"start": 585,
"end": 795
}
|
class ____ allows to assemble a HttpContent and a HttpResponse into one "packet" and so more
* efficient write it through the pipeline.
*
* @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
*/
|
which
|
java
|
spring-projects__spring-framework
|
spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java
|
{
"start": 17889,
"end": 18429
}
|
class ____ {
@Bean
public PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("myLabel", "LABEL");
props.setProperty("myTimeout", "5");
props.setProperty("myTransactionManager", "qualifiedTransactionManager");
pspc.setProperties(props);
return pspc;
}
}
@Configuration
@EnableTransactionManagement
@Import(PlaceholderConfig.class)
static
|
PlaceholderConfig
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/kstream/Suppressed.java
|
{
"start": 1607,
"end": 1872
}
|
interface ____ a buffer configuration that will strictly enforce size constraints
* (bytes and/or number of records) on the buffer, so it is suitable for reducing duplicate
* results downstream, but does not promise to eliminate them entirely.
*/
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/date/DateDiff.java
|
{
"start": 14138,
"end": 18413
}
|
interface ____ {
ExpressionEvaluator.Factory build(
Source source,
Part unitsEvaluator,
ExpressionEvaluator.Factory startTimestampEvaluator,
ExpressionEvaluator.Factory endTimestampEvaluator,
ZoneId zoneId
);
}
@Override
public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) {
ZoneId zoneId = configuration().zoneId();
if (startTimestamp.dataType() == DATETIME && endTimestamp.dataType() == DATETIME) {
return toEvaluator(toEvaluator, DateDiffConstantMillisEvaluator.Factory::new, DateDiffMillisEvaluator.Factory::new, zoneId);
} else if (startTimestamp.dataType() == DATE_NANOS && endTimestamp.dataType() == DATE_NANOS) {
return toEvaluator(toEvaluator, DateDiffConstantNanosEvaluator.Factory::new, DateDiffNanosEvaluator.Factory::new, zoneId);
} else if (startTimestamp.dataType() == DATE_NANOS && endTimestamp.dataType() == DATETIME) {
return toEvaluator(
toEvaluator,
DateDiffConstantNanosMillisEvaluator.Factory::new,
DateDiffNanosMillisEvaluator.Factory::new,
zoneId
);
} else if (startTimestamp.dataType() == DATETIME && endTimestamp.dataType() == DATE_NANOS) {
return toEvaluator(
toEvaluator,
DateDiffConstantMillisNanosEvaluator.Factory::new,
DateDiffMillisNanosEvaluator.Factory::new,
zoneId
);
}
throw new UnsupportedOperationException(
"Invalid types ["
+ startTimestamp.dataType()
+ ", "
+ endTimestamp.dataType()
+ "] "
+ "If you see this error, there is a bug in DateDiff.resolveType()"
);
}
private ExpressionEvaluator.Factory toEvaluator(
ToEvaluator toEvaluator,
DateDiffConstantFactory constantFactory,
DateDiffFactory dateDiffFactory,
ZoneId zoneId
) {
ExpressionEvaluator.Factory startTimestampEvaluator = toEvaluator.apply(startTimestamp);
ExpressionEvaluator.Factory endTimestampEvaluator = toEvaluator.apply(endTimestamp);
if (unit.foldable()) {
try {
Part datePartField = Part.resolve(BytesRefs.toString(unit.fold(toEvaluator.foldCtx())));
return constantFactory.build(source(), datePartField, startTimestampEvaluator, endTimestampEvaluator, zoneId);
} catch (IllegalArgumentException e) {
throw new InvalidArgumentException("invalid unit format for [{}]: {}", sourceText(), e.getMessage());
}
}
ExpressionEvaluator.Factory unitEvaluator = toEvaluator.apply(unit);
return dateDiffFactory.build(source(), unitEvaluator, startTimestampEvaluator, endTimestampEvaluator, zoneId);
}
@Override
protected TypeResolution resolveType() {
if (childrenResolved() == false) {
return new TypeResolution("Unresolved children");
}
String operationName = sourceText();
TypeResolution resolution = isString(unit, sourceText(), FIRST).and(
TypeResolutions.isType(startTimestamp, DataType::isDate, operationName, SECOND, "datetime or date_nanos")
).and(TypeResolutions.isType(endTimestamp, DataType::isDate, operationName, THIRD, "datetime or date_nanos"));
if (resolution.unresolved()) {
return resolution;
}
return TypeResolution.TYPE_RESOLVED;
}
@Override
public boolean foldable() {
return unit.foldable() && startTimestamp.foldable() && endTimestamp.foldable();
}
@Override
public DataType dataType() {
return DataType.INTEGER;
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new DateDiff(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2), configuration());
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, DateDiff::new, children().get(0), children().get(1), children().get(2), configuration());
}
}
|
DateDiffConstantFactory
|
java
|
google__jimfs
|
jimfs/src/test/java/com/google/common/jimfs/AbstractJimfsIntegrationTest.java
|
{
"start": 2187,
"end": 3373
}
|
class ____ {
private final Path path;
private FileTime accessTime;
private FileTime modifiedTime;
FileTimeTester(Path path) throws IOException {
this.path = path;
BasicFileAttributes attrs = attrs();
accessTime = attrs.lastAccessTime();
modifiedTime = attrs.lastModifiedTime();
}
private BasicFileAttributes attrs() throws IOException {
return Files.readAttributes(path, BasicFileAttributes.class);
}
public void assertAccessTimeChanged() throws IOException {
FileTime t = attrs().lastAccessTime();
assertThat(t).isNotEqualTo(accessTime);
accessTime = t;
}
public void assertAccessTimeDidNotChange() throws IOException {
FileTime t = attrs().lastAccessTime();
assertThat(t).isEqualTo(accessTime);
}
public void assertModifiedTimeChanged() throws IOException {
FileTime t = attrs().lastModifiedTime();
assertThat(t).isNotEqualTo(modifiedTime);
modifiedTime = t;
}
public void assertModifiedTimeDidNotChange() throws IOException {
FileTime t = attrs().lastModifiedTime();
assertThat(t).isEqualTo(modifiedTime);
}
}
}
|
FileTimeTester
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java
|
{
"start": 3136,
"end": 3550
}
|
class ____ implements ReportingService<ThreadPoolInfo>, Scheduler, TimeProvider {
private static final Logger logger = LogManager.getLogger(ThreadPool.class);
/**
* List of names that identify Java thread pools that are created in {@link ThreadPool#ThreadPool}. The pools themselves are constructed
* and configured using {@link DefaultBuiltInExecutorBuilders}.
*/
public static
|
ThreadPool
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java
|
{
"start": 3419,
"end": 5865
}
|
class ____ extends JoranConfigurator {
private final LoggingInitializationContext initializationContext;
SpringBootJoranConfigurator(LoggingInitializationContext initializationContext) {
this.initializationContext = initializationContext;
}
@Override
protected void sanityCheck(Model topModel) {
super.sanityCheck(topModel);
performCheck(new SpringProfileIfNestedWithinSecondPhaseElementSanityChecker(), topModel);
}
@Override
protected void addModelHandlerAssociations(DefaultProcessor defaultProcessor) {
defaultProcessor.addHandler(SpringPropertyModel.class,
(handlerContext, handlerMic) -> new SpringPropertyModelHandler(this.context,
this.initializationContext.getEnvironment()));
defaultProcessor.addHandler(SpringProfileModel.class,
(handlerContext, handlerMic) -> new SpringProfileModelHandler(this.context,
this.initializationContext.getEnvironment()));
super.addModelHandlerAssociations(defaultProcessor);
}
@Override
public void addElementSelectorAndActionAssociations(RuleStore ruleStore) {
super.addElementSelectorAndActionAssociations(ruleStore);
ruleStore.addRule(new ElementSelector("configuration/springProperty"), SpringPropertyAction::new);
ruleStore.addRule(new ElementSelector("*/springProfile"), SpringProfileAction::new);
ruleStore.addTransparentPathPart("springProfile");
}
@Override
public void buildModelInterpretationContext() {
super.buildModelInterpretationContext();
this.modelInterpretationContext.setConfiguratorSupplier(() -> {
SpringBootJoranConfigurator configurator = new SpringBootJoranConfigurator(this.initializationContext);
configurator.setContext(this.context);
return configurator;
});
}
boolean configureUsingAotGeneratedArtifacts() {
if (!new PatternRules(getContext()).load()) {
return false;
}
Model model = new ModelReader().read();
processModel(model);
registerSafeConfiguration(model);
return true;
}
@Override
public void processModel(Model model) {
super.processModel(model);
if (!NativeDetector.inNativeImage() && isAotProcessingInProgress()) {
getContext().putObject(BeanFactoryInitializationAotContribution.class.getName(),
new LogbackConfigurationAotContribution(model, getModelInterpretationContext(), getContext()));
}
}
private boolean isAotProcessingInProgress() {
return Boolean.getBoolean(AbstractAotProcessor.AOT_PROCESSING);
}
static final
|
SpringBootJoranConfigurator
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTypeTest.java
|
{
"start": 1352,
"end": 5453
}
|
class ____ extends ContextTestSupport {
@Test
public void testUnknownType() throws Exception {
try {
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
weaveByType(SplitDefinition.class).replace().to("mock:xxx");
}
});
fail("Should hve thrown exception");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("There are no outputs which matches: SplitDefinition in the route"),
e.getMessage());
}
}
@Test
public void testReplace() throws Exception {
// START SNIPPET: e1
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// weave by type in the route
// and replace it with the following route path
weaveByType(LogDefinition.class).replace().multicast().to("mock:a").to("mock:b");
}
});
// END SNIPPET: e1
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:b").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Test
public void testRemove() throws Exception {
// START SNIPPET: e2
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// weave the type in the route and remove it
weaveByType(TransformDefinition.class).remove();
}
});
// END SNIPPET: e2
getMockEndpoint("mock:result").expectedBodiesReceived("World");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Test
public void testBefore() throws Exception {
// START SNIPPET: e3
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// weave the type in the route and remove it
// and insert the following route path before the adviced node
weaveByType(ToDefinition.class).before().transform(constant("Bye World"));
}
});
// END SNIPPET: e3
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Test
public void testAfter() throws Exception {
// START SNIPPET: e4
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// weave the type in the route and remove it
// and insert the following route path after the adviced node
weaveByType(ToDefinition.class).after().transform(constant("Bye World"));
}
});
// END SNIPPET: e4
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
Object out = template.requestBody("direct:start", "World");
assertEquals("Bye World", out);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// START SNIPPET: e5
from("direct:start").transform(simple("Hello ${body}")).log("Got ${body}").to("mock:result");
// END SNIPPET: e5
}
};
}
}
|
AdviceWithTypeTest
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/SerializationFeature.java
|
{
"start": 520,
"end": 1115
}
|
enum ____ implements ConfigFeature
{
/*
/**********************************************************************
/* Generic output features
/**********************************************************************
*/
/**
* Feature that can be enabled to make root value (usually JSON
* Object but can be any type) wrapped within a single property
* JSON object, where key as the "root name", as determined by
* annotation introspector (esp. for JAXB that uses
* <code>@XmlRootElement.name</code>) or fallback (non-qualified
*
|
SerializationFeature
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringScriptTest.java
|
{
"start": 1158,
"end": 1810
}
|
class ____ extends ContextTestSupport {
protected MockEndpoint resultEndpoint;
@Test
public void testScript() throws Exception {
resultEndpoint.expectedBodiesReceived("Hello");
sendBody("direct:start", "Hello");
resultEndpoint.assertIsSatisfied();
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
resultEndpoint = getMockEndpoint("mock:result");
}
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/script.xml");
}
}
|
SpringScriptTest
|
java
|
quarkusio__quarkus
|
extensions/scheduler/api/src/main/java/io/quarkus/scheduler/Scheduler.java
|
{
"start": 7786,
"end": 7962
}
|
class ____ either represent a CDI bean or declare a public no-args constructor.
* <p>
* In case of CDI, there must be exactly one bean that has the specified
|
must
|
java
|
google__guice
|
extensions/grapher/test/com/google/inject/grapher/TransitiveDependencyVisitorTest.java
|
{
"start": 5677,
"end": 5993
}
|
class ____ implements Provider<ConstructedClass> {
@Inject E e;
ConstructedClassProvider() {}
@Inject
ConstructedClassProvider(A a, B b, C c) {}
@Inject
void setF(F f) {}
@Override
public ConstructedClass get() {
return null;
}
}
private static
|
ConstructedClassProvider
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/Multimaps.java
|
{
"start": 23100,
"end": 28483
}
|
class ____<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractSortedSetMultimap<K, V> {
transient Supplier<? extends SortedSet<V>> factory;
transient @Nullable Comparator<? super V> valueComparator;
CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
valueComparator = factory.get().comparator();
}
@Override
Set<K> createKeySet() {
return createMaybeNavigableKeySet();
}
@Override
Map<K, Collection<V>> createAsMap() {
return createMaybeNavigableAsMap();
}
@Override
protected SortedSet<V> createCollection() {
return factory.get();
}
@Override
public @Nullable Comparator<? super V> valueComparator() {
return valueComparator;
}
/**
* @serialData the factory and the backing map
*/
@GwtIncompatible
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
stream.writeObject(backingMap());
}
@GwtIncompatible
@J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends SortedSet<V>>) requireNonNull(stream.readObject());
valueComparator = factory.get().comparator();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
setMap(map);
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
/**
* Copies each key-value mapping in {@code source} into {@code dest}, with its key and value
* reversed.
*
* <p>If {@code source} is an {@link ImmutableMultimap}, consider using {@link
* ImmutableMultimap#inverse} instead.
*
* @param source any multimap
* @param dest the multimap to copy into; usually empty
* @return {@code dest}
*/
@CanIgnoreReturnValue
public static <K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>>
M invertFrom(Multimap<? extends V, ? extends K> source, M dest) {
checkNotNull(dest);
for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
dest.put(entry.getValue(), entry.getKey());
}
return dest;
}
/**
* Returns a synchronized (thread-safe) multimap backed by the specified multimap. In order to
* guarantee serial access, it is critical that <b>all</b> access to the backing multimap is
* accomplished through the returned multimap.
*
* <p>It is imperative that the user manually synchronize on the returned multimap when accessing
* any of its collection views:
*
* {@snippet :
* Multimap<K, V> multimap = Multimaps.synchronizedMultimap(HashMultimap.create());
* ...
* Collection<V> values = multimap.get(key); // Needn't be in synchronized block
* ...
* synchronized (multimap) { // Synchronizing on multimap, not values!
* Iterator<V> i = values.iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }
* }
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link
* Multimap#replaceValues} methods return collections that aren't synchronized.
*
* <p>The returned multimap will be serializable if the specified multimap is serializable.
*
* @param multimap the multimap to be wrapped in a synchronized view
* @return a synchronized view of the specified multimap
*/
@J2ktIncompatible // Synchronized
public static <K extends @Nullable Object, V extends @Nullable Object>
Multimap<K, V> synchronizedMultimap(Multimap<K, V> multimap) {
return Synchronized.multimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified multimap. Query operations on the returned
* multimap "read through" to the specified multimap, and attempts to modify the returned
* multimap, either directly or through the multimap's views, result in an {@code
* UnsupportedOperationException}.
*
* <p>The returned multimap will be serializable if the specified multimap is serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified multimap
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
Multimap<K, V> unmodifiableMultimap(Multimap<K, V> delegate) {
if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) {
return delegate;
}
return new UnmodifiableMultimap<>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@InlineMe(
replacement = "checkNotNull(delegate)",
staticImports = "com.google.common.base.Preconditions.checkNotNull")
@Deprecated
public static <K, V> Multimap<K, V> unmodifiableMultimap(ImmutableMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
private static
|
CustomSortedSetMultimap
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java
|
{
"start": 11292,
"end": 11366
}
|
class ____ extends ParentClass {
}
@JsonTypeName("bar")
private static
|
Foo
|
java
|
apache__maven
|
impl/maven-cli/src/main/java/org/apache/maven/cling/logging/impl/LogbackConfiguration.java
|
{
"start": 1044,
"end": 1653
}
|
class ____ extends BaseSlf4jConfiguration {
@Override
public void setRootLoggerLevel(Level level) {
ch.qos.logback.classic.Level value =
switch (level) {
case DEBUG -> ch.qos.logback.classic.Level.DEBUG;
case INFO -> ch.qos.logback.classic.Level.INFO;
default -> ch.qos.logback.classic.Level.ERROR;
};
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(value);
}
@Override
public void activate() {
// no op
}
}
|
LogbackConfiguration
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentRequirementFieldTest.java
|
{
"start": 3124,
"end": 3425
}
|
interface ____ {",
" TestComponent create(@BindsInstance @Nullable Bar arg);",
"}",
"}");
Source bar =
CompilerTests.javaSource(
"test.Bar", // force one-string-per-line format
"package test;",
"",
"
|
Factory
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/filter/wall/TenantSelectTest4.java
|
{
"start": 971,
"end": 3050
}
|
class ____ extends TestCase {
private String sql = "SELECT a.*,b.name " +
"FROM vote_info a left join vote_item b on a.item_id=b.id " +
"where 1=1 limit 1,10";
private String expect_sql = "SELECT a.*, b.name, b.tenant, a.tenant" +
"\nFROM vote_info a" +
"\n\tLEFT JOIN vote_item b ON a.item_id = b.id" +
"\nWHERE 1 = 1" +
"\nLIMIT 1, 10";
private WallConfig config = new WallConfig();
private WallConfig config_callback = new WallConfig();
protected void setUp() throws Exception {
config.setTenantTablePattern("*");
config.setTenantColumn("tenant");
config_callback.setTenantCallBack(new TenantTestCallBack());
}
public void testMySql() throws Exception {
WallProvider.setTenantValue(123);
MySqlWallProvider provider = new MySqlWallProvider(config);
config.setSelectWhereAlwayTrueCheck(false);
WallCheckResult checkResult = provider.check(sql);
assertEquals(0, checkResult.getViolations().size());
String resultSql = SQLUtils.toSQLString(checkResult.getStatementList(), JdbcConstants.MYSQL);
assertEquals(expect_sql, resultSql);
provider.reset();
config.setSelectWhereAlwayTrueCheck(true);
checkResult = provider.check(sql);
assertEquals(1, checkResult.getViolations().size());
}
public void testMySql2() throws Exception {
MySqlWallProvider provider = new MySqlWallProvider(config_callback);
provider.getConfig().setSelectWhereAlwayTrueCheck(false);
WallCheckResult checkResult = provider.check(sql);
assertEquals(0, checkResult.getViolations().size());
String resultSql = SQLUtils.toSQLString(checkResult.getStatementList(), JdbcConstants.MYSQL);
assertEquals(expect_sql, resultSql);
provider.reset();
provider.getConfig().setSelectWhereAlwayTrueCheck(true);
checkResult = provider.check(sql);
assertEquals(1, checkResult.getViolations().size());
}
}
|
TenantSelectTest4
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineReader.java
|
{
"start": 1537,
"end": 1654
}
|
interface ____ for retrieving timeline information.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public
|
is
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/commit/ITestAbfsTaskManifestFileIO.java
|
{
"start": 1295,
"end": 1929
}
|
class ____ extends TestTaskManifestFileIO {
private final ABFSContractTestBinding binding;
public ITestAbfsTaskManifestFileIO() throws Exception {
binding = new ABFSContractTestBinding();
}
@BeforeEach
@Override
public void setup() throws Exception {
binding.setup();
super.setup();
}
@Override
protected Configuration createConfiguration() {
return AbfsCommitTestHelper.prepareTestConfiguration(binding);
}
@Override
protected AbstractFSContract createContract(final Configuration conf) {
return new AbfsFileSystemContract(conf, binding.isSecureMode());
}
}
|
ITestAbfsTaskManifestFileIO
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java
|
{
"start": 23004,
"end": 23797
}
|
class ____ {
@RequestMapping
public void handle() {
}
@PostJson("/postJson")
public void postJson() {
}
@GetMapping("/get")
public void get() {
}
@PostMapping(path = "/post", consumes = MediaType.APPLICATION_XML_VALUE)
public void post(@RequestBody(required = false) Foo foo) {
}
// gh-31962: The presence of multiple @RequestMappings is intentional.
@PatchMapping("/put")
@RequestMapping(path = "/put", method = RequestMethod.PUT) // local @RequestMapping overrides meta-annotations
@PostMapping("/put")
public void put() {
}
@DeleteMapping("/delete")
public void delete() {
}
@PatchMapping("/patch")
public void patch() {
}
}
@RequestMapping
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@
|
ComposedAnnotationController
|
java
|
apache__dubbo
|
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java
|
{
"start": 1239,
"end": 2574
}
|
class ____ implements Filter, Filter.Listener {
/**
* The filter is called or not
*/
private boolean called = false;
/**
* There has error after invoked
*/
private boolean error = false;
/**
* The returned result
*/
private String response;
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*
* @param invoker
* @param invocation
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
called = true;
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
response = String.valueOf(appResponse.getValue());
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
error = true;
}
/**
* Returns if the filter has called.
*/
public boolean hasCalled() {
return called;
}
/**
* Returns if there exists error.
*/
public boolean hasError() {
return error;
}
/**
* Returns the response.
*/
public String getResponse() {
return response;
}
}
|
MultipleRegistryCenterExportProviderFilter
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TransientOverrideAsPersistentTablePerClassTests.java
|
{
"start": 2007,
"end": 8648
}
|
class ____ {
@Test
public void testFindByRootClass(SessionFactoryScope scope) {
scope.inTransaction( session -> {
var editor = session.find( Employee.class, "Jane Smith" );
assertNotNull( editor );
assertEquals( "Senior Editor", editor.getTitle() );
var writer = session.find( Employee.class, "John Smith" );
assertThat( writer, instanceOf( Writer.class ) );
assertEquals( "Writing", writer.getTitle() );
assertNotNull( ( (Writer) writer ).getGroup() );
var group = ( (Writer) writer ).getGroup();
assertEquals( writer.getTitle(), group.getName() );
var jobEditor = session.find( Job.class, "Edit" );
assertSame( editor, jobEditor.getEmployee() );
var jobWriter = session.find( Job.class, "Write" );
assertSame( writer, jobWriter.getEmployee() );
} );
}
@Test
public void testFindBySubclass(SessionFactoryScope scope) {
scope.inTransaction( session -> {
var editor = session.find( Editor.class, "Jane Smith" );
assertNotNull( editor );
assertEquals( "Senior Editor", editor.getTitle() );
var writer = session.find( Writer.class, "John Smith" );
assertEquals( "Writing", writer.getTitle() );
assertNotNull( writer.getGroup() );
var group = writer.getGroup();
assertEquals( writer.getTitle(), group.getName() );
var jobEditor = session.find( Job.class, "Edit" );
assertSame( editor, jobEditor.getEmployee() );
var jobWriter = session.find( Job.class, "Write" );
assertSame( writer, jobWriter.getEmployee() );
} );
}
@Test
public void testQueryByRootClass(SessionFactoryScope scope) {
scope.inTransaction( session -> {
//noinspection removal
var employees = session.createQuery( "from Employee", Employee.class )
.getResultList();
assertEquals( 2, employees.size() );
employees.sort( Comparator.comparing( Employee::getName ) );
assertThat( employees.get( 0 ), instanceOf( Editor.class ) );
assertThat( employees.get( 1 ), instanceOf( Writer.class ) );
var editor = (Editor) employees.get( 0 );
assertEquals( "Senior Editor", editor.getTitle() );
var writer = (Writer) employees.get( 1 );
assertEquals( "Writing", writer.getTitle() );
assertNotNull( writer.getGroup() );
var group = writer.getGroup();
assertEquals( writer.getTitle(), group.getName() );
} );
}
@Test
public void testQueryByRootClassAndOverridenProperty(SessionFactoryScope scope) {
scope.inTransaction( session -> {
//noinspection removal
var editor = session.createQuery( "from Employee where title=:title", Employee.class )
.setParameter( "title", "Senior Editor" )
.getSingleResult();
assertThat( editor, instanceOf( Editor.class ) );
//noinspection removal
var writer = session.createQuery( "from Employee where title=:title", Employee.class )
.setParameter( "title", "Writing" )
.getSingleResult();
assertThat( writer, instanceOf( Writer.class ) );
assertNotNull( ( (Writer) writer ).getGroup() );
assertEquals( writer.getTitle(), ( (Writer) writer ).getGroup().getName() );
} );
}
@Test
public void testQueryByRootClassAndOverridenPropertyTreat(SessionFactoryScope scope) {
scope.inTransaction( session -> {
//noinspection removal
var editor = session.createQuery(
"from Employee e where treat( e as Editor ).title=:title",
Employee.class
)
.setParameter( "title", "Senior Editor" )
.getSingleResult();
assertThat( editor, instanceOf( Editor.class ) );
//noinspection removal
var writer = session.createQuery(
"from Employee e where treat( e as Writer).title=:title",
Employee.class
)
.setParameter( "title", "Writing" )
.getSingleResult();
assertThat( writer, instanceOf( Writer.class ) );
assertNotNull( ( (Writer) writer ).getGroup() );
assertEquals( writer.getTitle(), ( (Writer) writer ).getGroup().getName() );
} );
}
@Test
public void testQueryBySublassAndOverridenProperty(SessionFactoryScope scope) {
scope.inTransaction( session -> {
//noinspection removal
var editor = session.createQuery( "from Editor where title=:title", Editor.class )
.setParameter( "title", "Senior Editor" )
.getSingleResult();
assertThat( editor, instanceOf( Editor.class ) );
//noinspection removal
var writer = session.createQuery( "from Writer where title=:title", Writer.class )
.setParameter( "title", "Writing" )
.getSingleResult();
assertNotNull( writer.getGroup() );
assertEquals( writer.getTitle(), writer.getGroup().getName() );
} );
}
@Test
public void testCriteriaQueryByRootClassAndOverridenProperty(SessionFactoryScope scope) {
scope.inTransaction( session -> {
var builder = session.getCriteriaBuilder();
var query = builder.createQuery( Employee.class );
var root = query.from( Employee.class );
var parameter = builder.parameter( String.class, "title" );
var predicateEditor = builder.equal(
builder.treat( root, Editor.class ).get( "title" ),
parameter
);
query.where( predicateEditor );
//noinspection removal
var editor = session.createQuery( query )
.setParameter( "title", "Senior Editor" )
.getSingleResult();
assertThat( editor, instanceOf( Editor.class ) );
var predicateWriter = builder.equal(
builder.treat( root, Writer.class ).get( "title" ),
parameter
);
query.where( predicateWriter );
//noinspection removal
var writer = session.createQuery( query )
.setParameter( "title", "Writing" )
.getSingleResult();
assertThat( writer, instanceOf( Writer.class ) );
assertNotNull( ( (Writer) writer ).getGroup() );
assertEquals( writer.getTitle(), ( (Writer) writer ).getGroup().getName() );
} );
}
@BeforeEach
public void setupData(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Job jobEditor = new Job( "Edit" );
jobEditor.setEmployee( new Editor( "Jane Smith", "Senior Editor" ) );
Job jobWriter = new Job( "Write" );
jobWriter.setEmployee( new Writer( "John Smith", new Group( "Writing" ) ) );
Employee editor = jobEditor.getEmployee();
Employee writer = jobWriter.getEmployee();
Group group = Writer.class.cast( writer ).getGroup();
session.persist( editor );
session.persist( group );
session.persist( writer );
session.persist( jobEditor );
session.persist( jobWriter );
} );
}
@AfterEach
public void cleanupData(SessionFactoryScope scope) {
scope.dropData();
}
@Entity(name = "Employee")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name = "department")
public static abstract
|
TransientOverrideAsPersistentTablePerClassTests
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
|
{
"start": 7232,
"end": 7432
}
|
class ____ implements DialectFeatureCheck {
public boolean apply(Dialect dialect) {
return dialect.getIdentityColumnSupport().supportsIdentityColumns();
}
}
public static
|
SupportsIdentityColumns
|
java
|
spring-projects__spring-boot
|
module/spring-boot-reactor-netty/src/test/java/org/springframework/boot/reactor/netty/autoconfigure/NettyReactiveWebServerAutoConfigurationTests.java
|
{
"start": 3052,
"end": 3625
}
|
class ____ {
private final NettyServerCustomizer customizer = mock(NettyServerCustomizer.class);
DoubleRegistrationNettyServerCustomizerConfiguration() {
given(this.customizer.apply(any(HttpServer.class))).willAnswer((invocation) -> invocation.getArgument(0));
}
@Bean
NettyServerCustomizer serverCustomizer() {
return this.customizer;
}
@Bean
WebServerFactoryCustomizer<NettyReactiveWebServerFactory> nettyCustomizer() {
return (netty) -> netty.addServerCustomizers(this.customizer);
}
}
}
|
DoubleRegistrationNettyServerCustomizerConfiguration
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
|
{
"start": 286904,
"end": 289326
}
|
class ____ extends RexShuttle {
private final Set<Integer> jsonInputFields;
JsonFunctionRexRewriter(Set<Integer> jsonInputFields) {
this.jsonInputFields = jsonInputFields;
}
@Override
public RexNode visitCall(RexCall call) {
if (call.getOperator() == SqlStdOperatorTable.JSON_OBJECT) {
final ImmutableList.Builder<RexNode> builder = ImmutableList.builder();
for (int i = 0; i < call.operands.size(); ++i) {
if ((i & 1) == 0 && i != 0) {
builder.add(forceChildJsonType(call.operands.get(i)));
} else {
builder.add(call.operands.get(i));
}
}
return rexBuilder.makeCall(SqlStdOperatorTable.JSON_OBJECT, builder.build());
}
if (call.getOperator() == SqlStdOperatorTable.JSON_ARRAY) {
final ImmutableList.Builder<RexNode> builder = ImmutableList.builder();
builder.add(call.operands.get(0));
for (int i = 1; i < call.operands.size(); ++i) {
builder.add(forceChildJsonType(call.operands.get(i)));
}
return rexBuilder.makeCall(SqlStdOperatorTable.JSON_ARRAY, builder.build());
}
return super.visitCall(call);
}
private RexNode forceChildJsonType(RexNode rexNode) {
final RexNode childResult = rexNode.accept(this);
if (isJsonResult(rexNode)) {
return rexBuilder.makeCall(SqlStdOperatorTable.JSON_TYPE_OPERATOR, childResult);
}
return childResult;
}
private boolean isJsonResult(RexNode rexNode) {
if (rexNode instanceof RexCall) {
final RexCall call = (RexCall) rexNode;
final SqlOperator operator = call.getOperator();
return operator == SqlStdOperatorTable.JSON_OBJECT
|| operator == SqlStdOperatorTable.JSON_ARRAY
|| operator == SqlStdOperatorTable.JSON_VALUE;
} else if (rexNode instanceof RexInputRef) {
final RexInputRef inputRef = (RexInputRef) rexNode;
return jsonInputFields.contains(inputRef.getIndex());
}
return false;
}
}
}
|
JsonFunctionRexRewriter
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/Hmac.java
|
{
"start": 973,
"end": 2109
}
|
class ____ {
private static final FastThreadLocal<Mac> MACS = new FastThreadLocal<Mac>() {
@Override
protected Mac initialValue() {
return newMac();
}
};
private static final String ALGORITM = "HmacSHA256";
private static final byte[] randomKey = new byte[16];
static {
new SecureRandom().nextBytes(randomKey);
}
private static Mac newMac() {
try {
SecretKeySpec keySpec = new SecretKeySpec(randomKey, ALGORITM);
Mac mac = Mac.getInstance(ALGORITM);
mac.init(keySpec);
return mac;
} catch (NoSuchAlgorithmException | InvalidKeyException exception) {
throw new IllegalStateException(exception);
}
}
static ByteBuffer sign(ByteBuffer input, int outLength) {
Mac mac = MACS.get();
mac.reset();
mac.update(input);
byte[] signBytes = mac.doFinal();
if (signBytes.length != outLength) {
signBytes = Arrays.copyOf(signBytes, outLength);
}
return ByteBuffer.wrap(signBytes);
}
private Hmac() { }
}
|
Hmac
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/filter/IgnoredTypesTest.java
|
{
"start": 510,
"end": 584
}
|
class ____ extends DatabindTestUtil
{
@JsonIgnoreType
|
IgnoredTypesTest
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MysqlShowCreateFullTextStatement.java
|
{
"start": 239,
"end": 877
}
|
class ____ extends MySqlStatementImpl implements MySqlShowStatement {
private FullTextType type;
private SQLName name;
public SQLName getName() {
return name;
}
public void setName(SQLName name) {
if (name != null) {
name.setParent(this);
}
this.name = name;
}
public FullTextType getType() {
return type;
}
public void setType(FullTextType type) {
this.type = type;
}
@Override
public void accept0(MySqlASTVisitor visitor) {
visitor.visit(this);
visitor.endVisit(this);
}
}
|
MysqlShowCreateFullTextStatement
|
java
|
apache__hadoop
|
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/CosNCopyFileContext.java
|
{
"start": 1174,
"end": 2051
}
|
class ____ {
private final ReentrantLock lock = new ReentrantLock();
private Condition readyCondition = lock.newCondition();
private AtomicBoolean copySuccess = new AtomicBoolean(true);
private AtomicInteger copiesFinish = new AtomicInteger(0);
public void lock() {
this.lock.lock();
}
public void unlock() {
this.lock.unlock();
}
public void awaitAllFinish(int waitCopiesFinish) throws InterruptedException {
while (this.copiesFinish.get() != waitCopiesFinish) {
this.readyCondition.await();
}
}
public void signalAll() {
this.readyCondition.signalAll();
}
public boolean isCopySuccess() {
return this.copySuccess.get();
}
public void setCopySuccess(boolean copySuccess) {
this.copySuccess.set(copySuccess);
}
public void incCopiesFinish() {
this.copiesFinish.addAndGet(1);
}
}
|
CosNCopyFileContext
|
java
|
bumptech__glide
|
library/test/src/test/java/com/bumptech/glide/util/FixedPreloadSizeProviderTest.java
|
{
"start": 383,
"end": 844
}
|
class ____ {
// containsExactly doesn't need a return value check.
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testReturnsGivenSize() {
int width = 500;
int height = 1234;
FixedPreloadSizeProvider<Object> provider = new FixedPreloadSizeProvider<>(width, height);
int[] size = provider.getPreloadSize(new Object(), 0, 0);
assertThat(size).asList().containsExactly(width, height);
}
}
|
FixedPreloadSizeProviderTest
|
java
|
apache__camel
|
core/camel-util/src/main/java/org/apache/camel/util/AnnotationHelper.java
|
{
"start": 5565,
"end": 6172
}
|
class ____) and if present, then returns
* the value attribute.
*
* @param method the method
* @param fqnAnnotationName the FQN of the annotation
* @return null if not annotated, otherwise the value, an empty string means annotation but has no
* value
*/
public static String getAnnotationValue(Method method, String fqnAnnotationName) {
return (String) getAnnotationValue(method, fqnAnnotationName, "value");
}
/**
* Checks if the method has been annotated with the given annotation (FQN
|
name
|
java
|
apache__camel
|
components/camel-debezium/camel-debezium-common/camel-debezium-common-component/src/main/java/org/apache/camel/component/debezium/configuration/EmbeddedDebeziumConfiguration.java
|
{
"start": 7345,
"end": 12866
}
|
class ____ by Debezium
*
* @return {@link Class}
*/
protected abstract Class<?> configureConnectorClass();
/**
* Create a specific {@link Configuration} for a concrete configuration
*
* @return {@link Configuration}
*/
protected abstract Configuration createConnectorConfiguration();
/**
* Validate a concrete configuration
*
* @return {@link ConfigurationValidation}
*/
protected abstract ConfigurationValidation validateConnectorConfiguration();
/**
* The Debezium connector type that is supported by Camel Debezium component.
*
* @return {@link String}
*/
public abstract String getConnectorDatabaseType();
/**
* Creates a Debezium configuration of type {@link Configuration} in order to be used in the engine.
*
* @return {@link Configuration}
*/
public Configuration createDebeziumConfiguration() {
final Configuration connectorConfiguration = createConnectorConfiguration();
ObjectHelper.notNull(connectorConfiguration, "createConnectorConfiguration");
return Configuration.create().with(createDebeziumEmbeddedEngineConfiguration())
.with(createConnectorConfiguration()).build();
}
private Configuration createDebeziumEmbeddedEngineConfiguration() {
final Configuration.Builder configBuilder = Configuration.create();
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.ENGINE_NAME, name);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.CONNECTOR_CLASS, connectorClass.getName());
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_STORAGE, offsetStorage);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_STORAGE_FILE_FILENAME,
offsetStorageFileName);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_STORAGE_KAFKA_TOPIC, offsetStorageTopic);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_STORAGE_KAFKA_PARTITIONS,
offsetStoragePartitions);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_STORAGE_KAFKA_REPLICATION_FACTOR,
offsetStorageReplicationFactor);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_COMMIT_POLICY, offsetCommitPolicy);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_FLUSH_INTERVAL_MS, offsetFlushIntervalMs);
addPropertyIfNotNull(configBuilder, AsyncEmbeddedEngine.OFFSET_COMMIT_TIMEOUT_MS, offsetCommitTimeoutMs);
if (internalKeyConverter != null && internalValueConverter != null) {
configBuilder.with("internal.key.converter", internalKeyConverter);
configBuilder.with("internal.value.converter", internalValueConverter);
}
// additional properties
applyAdditionalProperties(configBuilder, getAdditionalProperties());
return configBuilder.build();
}
protected static <T> void addPropertyIfNotNull(
final Configuration.Builder configBuilder,
final Field field, final T value) {
if (value != null) {
configBuilder.with(field, value);
}
}
protected static <T> void addPropertyIfNotNull(
final Configuration.Builder configBuilder,
final String key, final T value) {
if (value != null) {
configBuilder.with(key, value);
}
}
private void applyAdditionalProperties(
final Configuration.Builder configBuilder, final Map<String, Object> additionalProperties) {
if (!ObjectHelper.isEmpty(getAdditionalProperties())) {
additionalProperties.forEach((property, value) -> addPropertyIfNotNull(configBuilder, property, value));
}
}
/**
* Validate all configurations defined and return {@link ConfigurationValidation} instance which contains the
* validation results
*
* @return {@link ConfigurationValidation}
*/
public ConfigurationValidation validateConfiguration() {
final ConfigurationValidation embeddedEngineValidation = validateDebeziumEmbeddedEngineConfiguration();
// only if embeddedEngineValidation is true, we check the connector validation
if (embeddedEngineValidation.isValid()) {
final ConfigurationValidation connectorValidation = validateConnectorConfiguration();
ObjectHelper.notNull(connectorValidation, "validateConnectorConfiguration");
return connectorValidation;
}
return embeddedEngineValidation;
}
private ConfigurationValidation validateDebeziumEmbeddedEngineConfiguration() {
if (isFieldValueNotSet(name)) {
return ConfigurationValidation.notValid("Required field 'name' must be set.");
}
// check for offsetStorageFileName
if (offsetStorage.equals(DebeziumConstants.DEFAULT_OFFSET_STORAGE)
&& isFieldValueNotSet(offsetStorageFileName)) {
return ConfigurationValidation.notValid(String
.format("Required field 'offsetStorageFileName' must be set since 'offsetStorage' is set to '%s'",
DebeziumConstants.DEFAULT_OFFSET_STORAGE));
}
return ConfigurationValidation.valid();
}
protected static boolean isFieldValueNotSet(final Object field) {
return ObjectHelper.isEmpty(field);
}
/**
* The name of the Java
|
supported
|
java
|
quarkusio__quarkus
|
extensions/panache/mongodb-panache/deployment/src/test/java/io/quarkus/mongodb/panache/mongoentity/MongoEntityTest.java
|
{
"start": 284,
"end": 927
}
|
class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(
MongoEntityEntity.class,
MongoEntityRepository.class)
.addAsResource("application.properties"));
@Inject
MongoEntityRepository mongoEntityRepository;
@Test
public void testMongoEntity() {
assertEquals("mongoEntity", MongoEntityEntity.mongoDatabase().getName());
assertEquals("mongoEntity", mongoEntityRepository.mongoDatabase().getName());
}
}
|
MongoEntityTest
|
java
|
quarkusio__quarkus
|
extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/OidcClientFilterRevokedAccessTokenDevModeTest.java
|
{
"start": 3497,
"end": 3715
}
|
class ____ extends AbstractOidcClientRequestFilter {
}
@RegisterRestClient
@RegisterProvider(value = NamedClientRefreshDisabled.class)
@Path(MY_SERVER_RESOURCE_PATH)
public
|
DefaultClientRefreshDisabled
|
java
|
apache__camel
|
tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java
|
{
"start": 18932,
"end": 43240
}
|
class ____ extends ThreadGroup {
Throwable uncaughtException; // synchronize access to this
IsolatedThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
boolean doLog = false;
synchronized (this) {
// only remember the first one
if (uncaughtException == null) {
uncaughtException = throwable; // will be reported
// eventually
} else {
doLog = true;
}
}
if (doLog) {
getLog().warn("an additional exception was thrown", throwable);
}
}
}
private void joinNonDaemonThreads(ThreadGroup threadGroup) {
boolean foundNonDaemon;
do {
foundNonDaemon = false;
Collection<Thread> threads = getActiveThreads(threadGroup);
for (Thread thread : threads) {
if (thread.isDaemon()) {
continue;
}
foundNonDaemon = true; // try again; maybe more threads were
// created while we were busy
joinThread(thread, 0);
}
} while (foundNonDaemon);
}
private void joinThread(Thread thread, long timeoutMsecs) {
try {
getLog().debug("joining on thread " + thread);
thread.join(timeoutMsecs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // good practice if don't throw
getLog().warn("interrupted while joining against thread " + thread, e); // not
// expected!
}
// generally abnormal
if (thread.isAlive()) {
getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least "
+ timeoutMsecs + "msecs");
}
}
private void terminateThreads(ThreadGroup threadGroup) {
StopWatch watch = new StopWatch();
Set<Thread> uncooperativeThreads = new HashSet<>(); // these were not responsive
// to interruption
for (Collection<Thread> threads = getActiveThreads(threadGroup);
!threads.isEmpty();
threads = getActiveThreads(threadGroup), threads
.removeAll(uncooperativeThreads)) {
// Interrupt all threads we know about as of this instant (harmless
// if spuriously went dead (! isAlive())
// or if something else interrupted it ( isInterrupted() ).
for (Thread thread : threads) {
getLog().debug("interrupting thread " + thread);
thread.interrupt();
}
// Now join with a timeout and call stop() (assuming flags are set
// right)
for (Thread thread : threads) {
if (!thread.isAlive()) {
continue; // and, presumably it won't show up in
// getActiveThreads() next iteration
}
if (daemonThreadJoinTimeout <= 0) {
joinThread(thread, 0); // waits until not alive; no timeout
continue;
}
long timeout = daemonThreadJoinTimeout - watch.taken();
if (timeout > 0) {
joinThread(thread, timeout);
}
if (!thread.isAlive()) {
continue;
}
uncooperativeThreads.add(thread); // ensure we don't process
// again
if (stopUnresponsiveDaemonThreads) {
getLog().warn("thread " + thread + " is unresponsive to interruption and will be left to run");
// Try to interrupt again
thread.interrupt();
} else {
getLog().warn("thread " + thread
+ " will linger despite being asked to die via interruption");
}
}
}
if (!uncooperativeThreads.isEmpty()) {
getLog().warn("NOTE: "
+ uncooperativeThreads.size()
+ " thread(s) did not finish despite being asked to "
+ " via interruption. This is not a problem with exec:java, it is a problem with the running code."
+ " Although not serious, it should be remedied.");
} else {
int activeCount = threadGroup.activeCount();
if (activeCount != 0) {
// TODO this may be nothing; continue on anyway; perhaps don't
// even log in future
Thread[] threadsArray = new Thread[1];
threadGroup.enumerate(threadsArray);
if (getLog().isDebugEnabled()) {
getLog().debug("strange; " + activeCount + " thread(s) still active in the group "
+ threadGroup + " such as " + threadsArray[0]);
}
}
}
}
private Collection<Thread> getActiveThreads(ThreadGroup threadGroup) {
Thread[] threads = new Thread[threadGroup.activeCount()];
int numThreads = threadGroup.enumerate(threads);
Collection<Thread> result = new ArrayList<>(numThreads);
for (int i = 0; i < threads.length && threads[i] != null; i++) {
result.add(threads[i]);
}
// note: the result should be modifiable
return result;
}
/**
* Pass any given system properties to the java system properties.
*/
private void setSystemProperties() {
if (systemProperties != null) {
originalSystemProperties = System.getProperties();
for (Property systemProperty : systemProperties) {
String value = systemProperty.getValue();
System.setProperty(systemProperty.getKey(), value == null ? "" : value);
}
}
}
private boolean detectKameletOnClassPath() {
List<Dependency> deps = project.getCompileDependencies();
for (Dependency dep : deps) {
if ("org.apache.camel".equals(dep.getGroupId()) && "camel-kamelet-main".equals(dep.getArtifactId())) {
getLog().info("camel-kamelet-main detected on classpath");
return true;
}
}
// maybe there are Kamelet YAML files
List<Resource> resources = project.getResources();
for (Resource res : resources) {
File dir = new File(res.getDirectory());
File kamelets = new File(dir, "kamelets");
if (kamelets.exists() && kamelets.isDirectory()) {
getLog().info("Kamelets YAML files detected in directory " + kamelets);
return true;
}
}
return false;
}
/**
* Set up a classloader for the execution of the main class.
*
* @return the classloader
* @throws MojoExecutionException
*/
private ClassLoader getClassLoader() throws MojoExecutionException, MojoFailureException {
final List<Artifact> classpath = getClasspath();
final List<URL> classpathURLs = new ArrayList<>(classpath.size());
try {
for (Artifact artifact : classpath) {
File file = artifact.getFile();
if (file != null) {
classpathURLs.add(file.toURI().toURL());
}
}
} catch (MalformedURLException e) {
throw new MojoExecutionException("Error during setting up classpath", e);
}
if (logClasspath) {
getLog().info("Classpath:");
for (URL url : classpathURLs) {
getLog().info(" " + url.getFile());
}
}
return new URLClassLoader(classpathURLs.toArray(new URL[0]));
}
/**
* @return the list of artifacts corresponding to the classpath to use when launching the application
*/
protected List<Artifact> getClasspath() throws MojoExecutionException, MojoFailureException {
final List<Artifact> classpath = new ArrayList<>();
// project classpath must be first
this.addRelevantProjectDependenciesToClasspath(classpath);
// and extra plugin classpath
this.addExtraPluginDependenciesToClasspath(classpath);
// and plugin classpath last
this.addRelevantPluginDependenciesToClasspath(classpath);
if (!loggingLevel.equals("OFF")) {
getLog().info("Using built-in logging level: " + loggingLevel);
// and extra plugin classpath
this.addConsoleLogDependenciesToClasspath(classpath);
// setup logging which can only be done by copying log4j.properties to project output to be in classpath
try {
String out = LOG4J_TEMPLATE.replace("@@@LOGGING_LEVEL@@@", loggingLevel);
IOHelper.writeText(out, new File(project.getBuild().getOutputDirectory() + "/log4j2.properties"));
} catch (Exception e) {
throw new MojoFailureException("Error configuring loggingLevel", e);
}
}
return classpath;
}
/**
* Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and
* ExecutableDependency into consideration.
*
* @param classpath the list of artifacts representing the classpath to which artifacts should be
* added
* @throws MojoExecutionException
*/
private void addRelevantPluginDependenciesToClasspath(List<Artifact> classpath) throws MojoExecutionException {
if (hasCommandlineArgs()) {
arguments = parseCommandlineArgs();
}
for (Artifact classPathElement : this.determineRelevantPluginDependencies()) {
// we must skip org.osgi.core, otherwise we get a
// java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set
if (classPathElement.getArtifactId().equals("org.osgi.core")) {
if (getLog().isDebugEnabled()) {
getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/"
+ classPathElement.getArtifactId() + "/" + classPathElement.getVersion());
}
continue;
}
getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId()
+ " to classpath");
classpath.add(classPathElement);
}
}
/**
* Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and
* ExecutableDependency into consideration.
*
* @param classpath the list of artifacts representing the classpath to which artifacts should be
* added
* @throws MojoExecutionException
*/
private void addExtraPluginDependenciesToClasspath(List<Artifact> classpath) throws MojoExecutionException {
if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) {
return;
}
final Set<Artifact> artifacts = new HashSet<>(this.pluginDependencies);
for (Artifact artifact : artifacts) {
if (artifact.getArtifactId().equals(extraPluginDependencyArtifactId)
|| artifact.getArtifactId().equals(extendedPluginDependencyArtifactId)) {
getLog().debug("Adding extra plugin dependency artifact: " + artifact.getArtifactId()
+ " to classpath");
classpath.add(artifact);
// add the transient dependencies of this artifact
Set<Artifact> deps = resolveExecutableDependencies(artifact, true);
if (deps != null) {
for (Artifact dep : deps) {
getLog().debug("Adding extra plugin dependency artifact: " + dep.getArtifactId()
+ " to classpath");
classpath.add(dep);
}
}
}
}
}
/**
* Adds the JARs needed for using the built-in logging to console
*/
private void addConsoleLogDependenciesToClasspath(List<Artifact> classpath) {
Set<Artifact> artifacts = new HashSet<>(this.pluginDependencies);
for (Artifact artifact : artifacts) {
// add these loggers in the beginning so they are first
if (artifact.getArtifactId().equals("jansi")) {
// jansi for logging in color
classpath.add(0, artifact);
} else if (artifact.getGroupId().equals("org.apache.logging.log4j")) {
// add log4j as this is needed
classpath.add(0, artifact);
} else if (artifact.getArtifactId().equals("camel-maven-plugin")) {
// add ourselves
classpath.add(0, artifact);
}
}
}
/**
* Add any relevant project dependencies to the classpath. Takes includeProjectDependencies into consideration.
*
* @param classpath the list of artifacts representing the classpath to which artifacts should be
* added
* @throws MojoExecutionException
*/
private void addRelevantProjectDependenciesToClasspath(List<Artifact> classpath) throws MojoExecutionException {
if (this.includeProjectDependencies) {
getLog().debug("Project Dependencies will be included.");
File mainClasses = new File(project.getBuild().getOutputDirectory());
getLog().debug("Adding to classpath : " + mainClasses);
classpath.add(
new ProjectArtifact(project) {
@Override
public File getFile() {
return mainClasses;
}
});
Set<Artifact> dependencies = CastUtils.cast(project.getArtifacts());
// system scope dependencies are not returned by maven 2.0. See
// MEXEC-17
dependencies.addAll(getAllNonTestScopedDependencies());
for (Artifact classPathElement : dependencies) {
getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId()
+ " to classpath");
classpath.add(classPathElement);
}
} else {
getLog().debug("Project Dependencies will be excluded.");
}
}
private Collection<Artifact> getAllNonTestScopedDependencies() throws MojoExecutionException {
List<Artifact> answer = new ArrayList<>();
for (Artifact artifact : getAllDependencies()) {
// do not add test artifacts
if (!artifact.getScope().equals(Artifact.SCOPE_TEST)) {
answer.add(artifact);
}
}
return answer;
}
// generic method to retrieve all the transitive dependencies
private Collection<Artifact> getAllDependencies() throws MojoExecutionException {
List<Artifact> artifacts = new ArrayList<>();
for (Dependency dependency : project.getDependencies()) {
String groupId = dependency.getGroupId();
String artifactId = dependency.getArtifactId();
VersionRange versionRange;
try {
versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new MojoExecutionException("unable to parse version", e);
}
String type = dependency.getType();
if (type == null) {
type = "jar";
}
String classifier = dependency.getClassifier();
boolean optional = dependency.isOptional();
String scope = dependency.getScope();
if (scope == null) {
scope = Artifact.SCOPE_COMPILE;
}
Artifact art = this.artifactFactory.createDependencyArtifact(groupId, artifactId, versionRange,
type, classifier, scope, null, optional);
if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
art.setFile(new File(dependency.getSystemPath()));
}
List<String> exclusions = new ArrayList<>();
for (Exclusion exclusion : dependency.getExclusions()) {
exclusions.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
}
ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
art.setDependencyFilter(newFilter);
artifacts.add(art);
}
return artifacts;
}
/**
* Determine all plugin dependencies relevant to the executable. Takes includePlugins, and the executableDependency
* into consideration.
*
* @return a set of Artifact objects. (Empty set is returned if there are no relevant plugin
* dependencies.)
* @throws MojoExecutionException
*/
@Override
protected Set<Artifact> determineRelevantPluginDependencies() throws MojoExecutionException {
Set<Artifact> relevantDependencies;
if (this.includePluginDependencies) {
if (this.executableDependency == null) {
getLog().debug("All Plugin Dependencies will be included.");
relevantDependencies = new HashSet<>(this.pluginDependencies);
} else {
getLog().debug("Selected plugin Dependencies will be included.");
Artifact executableArtifact = this.findExecutableArtifact();
Artifact executablePomArtifact = this.getExecutablePomArtifact(executableArtifact);
relevantDependencies = this.resolveExecutableDependencies(executablePomArtifact, false);
}
} else {
getLog().debug("Only Direct Plugin Dependencies will be included.");
PluginDescriptor descriptor = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
try {
relevantDependencies = artifactResolver
.resolveTransitively(MavenMetadataSource
.createArtifacts(this.artifactFactory,
descriptor.getPlugin().getDependencies(),
null, null, null),
this.project.getArtifact(),
Collections.emptyMap(),
this.localRepository,
this.remoteRepositories,
metadataSource,
new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME),
Collections.emptyList())
.getArtifacts();
} catch (Exception ex) {
throw new MojoExecutionException(
"Encountered problems resolving dependencies of the plugin "
+ "in preparation for its execution.",
ex);
}
}
return relevantDependencies;
}
/**
* Get the artifact which refers to the POM of the executable artifact.
*
* @param executableArtifact this artifact refers to the actual assembly.
* @return an artifact which refers to the POM of the executable artifact.
*/
private Artifact getExecutablePomArtifact(Artifact executableArtifact) {
return this.artifactFactory.createBuildArtifact(executableArtifact.getGroupId(), executableArtifact
.getArtifactId(), executableArtifact.getVersion(), "pom");
}
/**
* Examine the plugin dependencies to find the executable artifact.
*
* @return an artifact which refers to the actual executable tool (not a POM)
* @throws MojoExecutionException
*/
@Override
protected Artifact findExecutableArtifact() throws MojoExecutionException {
// ILimitedArtifactIdentifier execToolAssembly =
// this.getExecutableToolAssembly();
Artifact executableTool = null;
for (Artifact pluginDep : this.pluginDependencies) {
if (this.executableDependency.matches(pluginDep)) {
executableTool = pluginDep;
break;
}
}
if (executableTool == null) {
throw new MojoExecutionException(
"No dependency of the plugin matches the specified executableDependency."
+ " Specified executableToolAssembly is: "
+ executableDependency.toString());
}
return executableTool;
}
private Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact, boolean ignoreFailures)
throws MojoExecutionException {
Set<Artifact> executableDependencies = null;
try {
MavenProject executableProject = this.projectBuilder.buildFromRepository(executablePomArtifact,
this.remoteRepositories,
this.localRepository);
// get all the dependencies for the executable project
List<Dependency> dependencies = executableProject.getDependencies();
// make Artifacts of all the dependencies
Set<Artifact> dependencyArtifacts
= MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies,
null, null, null);
// not forgetting the Artifact of the project itself
dependencyArtifacts.add(executableProject.getArtifact());
// resolve runtime dependencies transitively to obtain a comprehensive list of assemblies
ArtifactResolutionRequest request = new ArtifactResolutionRequest()
.setArtifact(executablePomArtifact)
.setResolveRoot(false)
.setArtifactDependencies(dependencyArtifacts)
.setManagedVersionMap(Collections.emptyMap())
.setLocalRepository(localRepository)
.setRemoteRepositories(remoteRepositories)
.setCollectionFilter(new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME))
.setListeners(Collections.emptyList());
ArtifactResolutionResult result = artifactResolver.resolve(request);
executableDependencies = CastUtils.cast(result.getArtifacts());
} catch (Exception ex) {
if (ignoreFailures) {
getLog().debug("Ignoring maven resolving dependencies failure " + ex.getMessage());
} else {
throw new MojoExecutionException(
"Encountered problems resolving dependencies of the executable "
+ "in preparation for its execution.",
ex);
}
}
return executableDependencies;
}
/**
* Stop program execution for nn millis.
*
* @param millis the number of millis-seconds to wait for, <code>0</code> stops program forever.
*/
private void waitFor(long millis) {
Object lock = new Object();
synchronized (lock) {
try {
lock.wait(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // good practice if don't throw
getLog().warn("Spuriously interrupted while waiting for " + millis + "ms", e);
}
}
}
}
|
IsolatedThreadGroup
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java
|
{
"start": 2028,
"end": 13177
}
|
class ____ {
private final OidcClientRegistrationHttpMessageConverter messageConverter = new OidcClientRegistrationHttpMessageConverter();
@Test
public void supportsWhenOidcClientRegistrationThenTrue() {
assertThat(this.messageConverter.supports(OidcClientRegistration.class)).isTrue();
}
@Test
public void setClientRegistrationConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.messageConverter.setClientRegistrationConverter(null))
.withMessageContaining("clientRegistrationConverter cannot be null");
}
@Test
public void setClientRegistrationParametersConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.messageConverter.setClientRegistrationParametersConverter(null))
.withMessageContaining("clientRegistrationParametersConverter cannot be null");
}
@Test
public void readInternalWhenRequiredParametersThenSuccess() {
// @formatter:off
String clientRegistrationRequest = "{\n"
+ " \"redirect_uris\": [\n"
+ " \"https://client.example.com\"\n"
+ " ]\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(),
HttpStatus.OK);
OidcClientRegistration clientRegistration = this.messageConverter.readInternal(OidcClientRegistration.class,
response);
assertThat(clientRegistration.getClaims()).hasSize(1);
assertThat(clientRegistration.getRedirectUris()).containsOnly("https://client.example.com");
}
@Test
public void readInternalWhenValidParametersThenSuccess() throws Exception {
// @formatter:off
String clientRegistrationRequest = "{\n"
+ " \"client_id\": \"client-id\",\n"
+ " \"client_id_issued_at\": 1607633867,\n"
+ " \"client_secret\": \"client-secret\",\n"
+ " \"client_secret_expires_at\": 1607637467,\n"
+ " \"client_name\": \"client-name\",\n"
+ " \"redirect_uris\": [\n"
+ " \"https://client.example.com\"\n"
+ " ],\n"
+ " \"post_logout_redirect_uris\": [\n"
+ " \"https://client.example.com/oidc-post-logout\"\n"
+ " ],\n"
+ " \"token_endpoint_auth_method\": \"client_secret_jwt\",\n"
+ " \"token_endpoint_auth_signing_alg\": \"HS256\",\n"
+ " \"grant_types\": [\n"
+ " \"authorization_code\",\n"
+ " \"client_credentials\"\n"
+ " ],\n"
+ " \"response_types\":[\n"
+ " \"code\"\n"
+ " ],\n"
+ " \"scope\": \"scope1 scope2\",\n"
+ " \"jwks_uri\": \"https://client.example.com/jwks\",\n"
+ " \"id_token_signed_response_alg\": \"RS256\",\n"
+ " \"a-claim\": \"a-value\"\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(),
HttpStatus.OK);
OidcClientRegistration clientRegistration = this.messageConverter.readInternal(OidcClientRegistration.class,
response);
assertThat(clientRegistration.getClientId()).isEqualTo("client-id");
assertThat(clientRegistration.getClientIdIssuedAt()).isEqualTo(Instant.ofEpochSecond(1607633867L));
assertThat(clientRegistration.getClientSecret()).isEqualTo("client-secret");
assertThat(clientRegistration.getClientSecretExpiresAt()).isEqualTo(Instant.ofEpochSecond(1607637467L));
assertThat(clientRegistration.getClientName()).isEqualTo("client-name");
assertThat(clientRegistration.getRedirectUris()).containsOnly("https://client.example.com");
assertThat(clientRegistration.getPostLogoutRedirectUris())
.containsOnly("https://client.example.com/oidc-post-logout");
assertThat(clientRegistration.getTokenEndpointAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue());
assertThat(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm())
.isEqualTo(MacAlgorithm.HS256.getName());
assertThat(clientRegistration.getGrantTypes()).containsExactlyInAnyOrder("authorization_code",
"client_credentials");
assertThat(clientRegistration.getResponseTypes()).containsOnly("code");
assertThat(clientRegistration.getScopes()).containsExactlyInAnyOrder("scope1", "scope2");
assertThat(clientRegistration.getJwkSetUrl()).isEqualTo(new URL("https://client.example.com/jwks"));
assertThat(clientRegistration.getIdTokenSignedResponseAlgorithm()).isEqualTo("RS256");
assertThat(clientRegistration.getClaimAsString("a-claim")).isEqualTo("a-value");
}
@Test
public void readInternalWhenClientSecretNoExpiryThenSuccess() {
// @formatter:off
String clientRegistrationRequest = "{\n"
+ " \"client_id\": \"client-id\",\n"
+ " \"client_secret\": \"client-secret\",\n"
+ " \"client_secret_expires_at\": 0,\n"
+ " \"redirect_uris\": [\n"
+ " \"https://client.example.com\"\n"
+ " ]\n"
+ "}\n";
// @formatter:on
MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(),
HttpStatus.OK);
OidcClientRegistration clientRegistration = this.messageConverter.readInternal(OidcClientRegistration.class,
response);
assertThat(clientRegistration.getClaims()).hasSize(3);
assertThat(clientRegistration.getClientId()).isEqualTo("client-id");
assertThat(clientRegistration.getClientSecret()).isEqualTo("client-secret");
assertThat(clientRegistration.getClientSecretExpiresAt()).isNull();
assertThat(clientRegistration.getRedirectUris()).containsOnly("https://client.example.com");
}
@Test
public void readInternalWhenFailingConverterThenThrowException() {
String errorMessage = "this is not a valid converter";
this.messageConverter.setClientRegistrationConverter((source) -> {
throw new RuntimeException(errorMessage);
});
MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class)
.isThrownBy(() -> this.messageConverter.readInternal(OidcClientRegistration.class, response))
.withMessageContaining("An error occurred reading the OpenID Client Registration")
.withMessageContaining(errorMessage);
}
@Test
public void writeInternalWhenClientRegistrationThenSuccess() {
// @formatter:off
OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.clientId("client-id")
.clientIdIssuedAt(Instant.ofEpochSecond(1607633867))
.clientSecret("client-secret")
.clientSecretExpiresAt(Instant.ofEpochSecond(1607637467))
.clientName("client-name")
.redirectUri("https://client.example.com")
.postLogoutRedirectUri("https://client.example.com/oidc-post-logout")
.tokenEndpointAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue())
.tokenEndpointAuthenticationSigningAlgorithm(MacAlgorithm.HS256.getName())
.grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue())
.grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue())
.responseType(OAuth2AuthorizationResponseType.CODE.getValue())
.scope("scope1")
.scope("scope2")
.jwkSetUrl("https://client.example.com/jwks")
.idTokenSignedResponseAlgorithm(SignatureAlgorithm.RS256.getName())
.registrationAccessToken("registration-access-token")
.registrationClientUrl("https://auth-server.com/connect/register?client_id=1")
.claim("a-claim", "a-value")
.build();
// @formatter:on
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.messageConverter.writeInternal(clientRegistration, outputMessage);
String clientRegistrationResponse = outputMessage.getBodyAsString();
assertThat(clientRegistrationResponse).contains("\"client_id\":\"client-id\"");
assertThat(clientRegistrationResponse).contains("\"client_id_issued_at\":1607633867");
assertThat(clientRegistrationResponse).contains("\"client_secret\":\"client-secret\"");
assertThat(clientRegistrationResponse).contains("\"client_secret_expires_at\":1607637467");
assertThat(clientRegistrationResponse).contains("\"client_name\":\"client-name\"");
assertThat(clientRegistrationResponse).contains("\"redirect_uris\":[\"https://client.example.com\"]");
assertThat(clientRegistrationResponse)
.contains("\"post_logout_redirect_uris\":[\"https://client.example.com/oidc-post-logout\"]");
assertThat(clientRegistrationResponse).contains("\"token_endpoint_auth_method\":\"client_secret_jwt\"");
assertThat(clientRegistrationResponse).contains("\"token_endpoint_auth_signing_alg\":\"HS256\"");
assertThat(clientRegistrationResponse)
.contains("\"grant_types\":[\"authorization_code\",\"client_credentials\"]");
assertThat(clientRegistrationResponse).contains("\"response_types\":[\"code\"]");
assertThat(clientRegistrationResponse).contains("\"scope\":\"scope1 scope2\"");
assertThat(clientRegistrationResponse).contains("\"jwks_uri\":\"https://client.example.com/jwks\"");
assertThat(clientRegistrationResponse).contains("\"id_token_signed_response_alg\":\"RS256\"");
assertThat(clientRegistrationResponse).contains("\"registration_access_token\":\"registration-access-token\"");
assertThat(clientRegistrationResponse)
.contains("\"registration_client_uri\":\"https://auth-server.com/connect/register?client_id=1\"");
assertThat(clientRegistrationResponse).contains("\"a-claim\":\"a-value\"");
}
@Test
public void writeInternalWhenClientSecretNoExpiryThenSuccess() {
// @formatter:off
OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.clientId("client-id")
.clientSecret("client-secret")
.redirectUri("https://client.example.com")
.build();
// @formatter:on
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.messageConverter.writeInternal(clientRegistration, outputMessage);
String clientRegistrationResponse = outputMessage.getBodyAsString();
assertThat(clientRegistrationResponse).contains("\"client_id\":\"client-id\"");
assertThat(clientRegistrationResponse).contains("\"client_secret\":\"client-secret\"");
assertThat(clientRegistrationResponse).contains("\"client_secret_expires_at\":0");
assertThat(clientRegistrationResponse).contains("\"redirect_uris\":[\"https://client.example.com\"]");
}
@Test
public void writeInternalWhenWriteFailsThenThrowException() {
String errorMessage = "this is not a valid converter";
Converter<OidcClientRegistration, Map<String, Object>> failingConverter = (source) -> {
throw new RuntimeException(errorMessage);
};
this.messageConverter.setClientRegistrationParametersConverter(failingConverter);
// @formatter:off
OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.redirectUri("https://client.example.com")
.build();
// @formatter:off
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> this.messageConverter.writeInternal(clientRegistration, outputMessage))
.withMessageContaining("An error occurred writing the OpenID Client Registration")
.withMessageContaining(errorMessage);
}
}
|
OidcClientRegistrationHttpMessageConverterTests
|
java
|
spring-projects__spring-framework
|
spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java
|
{
"start": 23047,
"end": 25035
}
|
class ____ {
@Test
void varargsMethodInvocationWithIndividualArguments() {
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted('blue', 1)";
String message = parser.parseExpression(expression)
.getValue(String.class);
assertThat(message).isEqualTo("blue is color #1");
}
@Test
void varargsMethodInvocationWithArgumentsAsObjectArray() {
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted(new Object[] {'blue', 1})";
String message = parser.parseExpression(expression)
.getValue(String.class);
assertThat(message).isEqualTo("blue is color #1");
}
@Test
void varargsMethodInvocationWithArgumentsAsInlineList() {
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted({'blue', 1})";
String message = parser.parseExpression(expression).getValue(String.class);
assertThat(message).isEqualTo("blue is color #1");
}
@Test
void varargsMethodInvocationWithTypeConversion() {
Method reverseStringsMethod = ReflectionUtils.findMethod(StringUtils.class, "reverseStrings", String[].class);
SimpleEvaluationContext evaluationContext = SimpleEvaluationContext.forReadOnlyDataBinding().build();
evaluationContext.setVariable("reverseStrings", reverseStringsMethod);
// String reverseStrings(String... strings)
// evaluates to "3.0, 2.0, 1.0, SpEL"
String expression = "#reverseStrings('SpEL', 1, 10F / 5, 3.0000)";
String message = parser.parseExpression(expression)
.getValue(evaluationContext, String.class);
assertThat(message).isEqualTo("3.0, 2.0, 1, SpEL");
}
@Test
void varargsMethodInvocationWithArgumentsAsStringArray() {
// evaluates to "blue is color #1"
String expression = "'%s is color #%s'.formatted(new String[] {'blue', 1})";
String message = parser.parseExpression(expression).getValue(String.class);
assertThat(message).isEqualTo("blue is color #1");
}
}
@Nested
|
Varargs
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/StructuredDataLookup.java
|
{
"start": 1187,
"end": 2222
}
|
class ____ extends AbstractLookup {
/**
* Key to obtain the id of a structured message.
*/
public static final String ID_KEY = "id";
/**
* Key to obtain the type of a structured message.
*/
public static final String TYPE_KEY = "type";
/**
* Looks up the value for the key using the data in the LogEvent.
* @param event The current LogEvent.
* @param key The key to be looked up, may be null.
* @return The value associated with the key.
*/
@Override
public String lookup(final LogEvent event, final String key) {
if (event == null || !(event.getMessage() instanceof StructuredDataMessage)) {
return null;
}
final StructuredDataMessage msg = (StructuredDataMessage) event.getMessage();
if (ID_KEY.equalsIgnoreCase(key)) {
return msg.getId().getName();
} else if (TYPE_KEY.equalsIgnoreCase(key)) {
return msg.getType();
}
return msg.get(key);
}
}
|
StructuredDataLookup
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/test/disruption/NetworkDisruption.java
|
{
"start": 10907,
"end": 13737
}
|
class ____ extends DisruptedLinks {
private final String bridgeNode;
private final Set<String> nodesSideOne;
private final Set<String> nodesSideTwo;
public Bridge(String bridgeNode, Set<String> nodesSideOne, Set<String> nodesSideTwo) {
super(Collections.singleton(bridgeNode), nodesSideOne, nodesSideTwo);
this.bridgeNode = bridgeNode;
this.nodesSideOne = nodesSideOne;
this.nodesSideTwo = nodesSideTwo;
assert nodesSideOne.isEmpty() == false;
assert nodesSideTwo.isEmpty() == false;
assert Sets.haveEmptyIntersection(nodesSideOne, nodesSideTwo);
assert nodesSideOne.contains(bridgeNode) == false && nodesSideTwo.contains(bridgeNode) == false;
}
public static Bridge random(Random random, String... nodes) {
return random(random, Sets.newHashSet(nodes));
}
public static Bridge random(Random random, Set<String> nodes) {
assert nodes.size() >= 3 : "bridge topology requires at least 3 nodes";
String bridgeNode = RandomPicks.randomFrom(random, nodes);
Set<String> nodesSideOne = new HashSet<>();
Set<String> nodesSideTwo = new HashSet<>();
for (String node : nodes) {
if (node.equals(bridgeNode) == false) {
if (nodesSideOne.isEmpty()) {
nodesSideOne.add(node);
} else if (nodesSideTwo.isEmpty()) {
nodesSideTwo.add(node);
} else if (random.nextBoolean()) {
nodesSideOne.add(node);
} else {
nodesSideTwo.add(node);
}
}
}
return new Bridge(bridgeNode, nodesSideOne, nodesSideTwo);
}
@Override
public boolean disrupt(String node1, String node2) {
if (nodesSideOne.contains(node1) && nodesSideTwo.contains(node2)) {
return true;
}
if (nodesSideOne.contains(node2) && nodesSideTwo.contains(node1)) {
return true;
}
return false;
}
public String getBridgeNode() {
return bridgeNode;
}
public Set<String> getNodesSideOne() {
return nodesSideOne;
}
public Set<String> getNodesSideTwo() {
return nodesSideTwo;
}
public String toString() {
return "bridge partition (super connected node: ["
+ bridgeNode
+ "], partition 1: "
+ nodesSideOne
+ " and partition 2: "
+ nodesSideTwo
+ ")";
}
}
public static
|
Bridge
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java
|
{
"start": 11359,
"end": 11759
}
|
class ____ implements OperationInvoker {
private final OperationInvoker invoker;
public ElasticSchedulerInvoker(OperationInvoker invoker) {
this.invoker = invoker;
}
@Override
public Object invoke(InvocationContext context) {
return Mono.fromCallable(() -> this.invoker.invoke(context)).subscribeOn(Schedulers.boundedElastic());
}
}
protected static final
|
ElasticSchedulerInvoker
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/spatial/CentroidPointAggregator.java
|
{
"start": 1522,
"end": 6228
}
|
class ____ {
public static CentroidState initSingle() {
return new CentroidState();
}
public static GroupingCentroidState initGrouping(BigArrays bigArrays) {
return new GroupingCentroidState(bigArrays);
}
public static void combine(CentroidState current, double xVal, double xDel, double yVal, double yDel, long count) {
current.add(xVal, xDel, yVal, yDel, count);
}
public static void combineIntermediate(CentroidState state, double xIn, double dx, double yIn, double dy, long count) {
if (count > 0) {
combine(state, xIn, dx, yIn, dy, count);
}
}
public static void evaluateIntermediate(CentroidState state, DriverContext driverContext, Block[] blocks, int offset) {
assert blocks.length >= offset + 5;
BlockFactory blockFactory = driverContext.blockFactory();
blocks[offset + 0] = blockFactory.newConstantDoubleBlockWith(state.xSum.value(), 1);
blocks[offset + 1] = blockFactory.newConstantDoubleBlockWith(state.xSum.delta(), 1);
blocks[offset + 2] = blockFactory.newConstantDoubleBlockWith(state.ySum.value(), 1);
blocks[offset + 3] = blockFactory.newConstantDoubleBlockWith(state.ySum.delta(), 1);
blocks[offset + 4] = blockFactory.newConstantLongBlockWith(state.count, 1);
}
public static Block evaluateFinal(CentroidState state, DriverContext driverContext) {
return state.toBlock(driverContext.blockFactory());
}
public static void combineIntermediate(
GroupingCentroidState current,
int groupId,
double xValue,
double xDelta,
double yValue,
double yDelta,
long count
) {
if (count > 0) {
current.add(xValue, xDelta, yValue, yDelta, count, groupId);
}
}
public static void evaluateIntermediate(
GroupingCentroidState state,
Block[] blocks,
int offset,
IntVector selected,
DriverContext driverContext
) {
assert blocks.length >= offset + 5;
try (
var xValuesBuilder = driverContext.blockFactory().newDoubleBlockBuilder(selected.getPositionCount());
var xDeltaBuilder = driverContext.blockFactory().newDoubleBlockBuilder(selected.getPositionCount());
var yValuesBuilder = driverContext.blockFactory().newDoubleBlockBuilder(selected.getPositionCount());
var yDeltaBuilder = driverContext.blockFactory().newDoubleBlockBuilder(selected.getPositionCount());
var countsBuilder = driverContext.blockFactory().newLongBlockBuilder(selected.getPositionCount());
) {
for (int i = 0; i < selected.getPositionCount(); i++) {
int group = selected.getInt(i);
if (group < state.xValues.size()) {
xValuesBuilder.appendDouble(state.xValues.get(group));
xDeltaBuilder.appendDouble(state.xDeltas.get(group));
yValuesBuilder.appendDouble(state.yValues.get(group));
yDeltaBuilder.appendDouble(state.yDeltas.get(group));
countsBuilder.appendLong(state.counts.get(group));
} else {
xValuesBuilder.appendDouble(0);
xDeltaBuilder.appendDouble(0);
yValuesBuilder.appendDouble(0);
yDeltaBuilder.appendDouble(0);
countsBuilder.appendLong(0);
}
}
blocks[offset + 0] = xValuesBuilder.build();
blocks[offset + 1] = xDeltaBuilder.build();
blocks[offset + 2] = yValuesBuilder.build();
blocks[offset + 3] = yDeltaBuilder.build();
blocks[offset + 4] = countsBuilder.build();
}
}
public static Block evaluateFinal(GroupingCentroidState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) {
try (BytesRefBlock.Builder builder = ctx.blockFactory().newBytesRefBlockBuilder(selected.getPositionCount())) {
for (int i = 0; i < selected.getPositionCount(); i++) {
int si = selected.getInt(i);
if (state.hasValue(si) && si < state.xValues.size()) {
BytesRef result = state.encodeCentroidResult(si);
builder.appendBytesRef(result);
} else {
builder.appendNull();
}
}
return builder.build();
}
}
private static BytesRef encode(double x, double y) {
return new BytesRef(WellKnownBinary.toWKB(new Point(x, y), ByteOrder.LITTLE_ENDIAN));
}
static
|
CentroidPointAggregator
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ModuleFactoryGeneratorTest.java
|
{
"start": 15413,
"end": 17009
}
|
class ____ implements"
+ " Factory<String> {",
" private final TestModule module;",
"",
" private TestModule_ProvideStringFactory(TestModule module) {",
" this.module = module;",
" }",
"",
// TODO(b/368129744): KSP should output the @Nullable annotation after this
// bug is fixed.
isJavac ? " @Override\n @Nullable" : " @Override",
" public String get() {",
" return provideString(module);",
" }",
"",
" public static TestModule_ProvideStringFactory create(TestModule module) {",
" return new TestModule_ProvideStringFactory(module);",
" }",
// TODO(b/368129744): KSP should output the @Nullable annotation after this
// bug is fixed.
isJavac ? "\n @Nullable" : "",
" public static String provideString(TestModule instance) {",
" return instance.provideString();",
" }",
"}"));
});
}
@Test public void multipleProvidesMethods() {
Source classXFile =
CompilerTests.javaSource("test.X",
"package test;",
"",
"import javax.inject.Inject;",
"",
"
|
TestModule_ProvideStringFactory
|
java
|
reactor__reactor-core
|
benchmarks/src/main/java/reactor/core/scrabble/ShakespearePlaysScrabble.java
|
{
"start": 2030,
"end": 2927
}
|
class ____ {
long value;
long get() {
return value;
}
MutableLong incAndSet() {
value++;
return this;
}
}
static Set<String> read(String resourceName) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(ShakespearePlaysScrabble.class.getClassLoader()
.getResourceAsStream(
resourceName))))
) {
return br.lines()
.map(String::toLowerCase)
.collect(Collectors.toSet());
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
static <T> Iterable<T> iterableOf(Spliterator<T> spliterator) {
return () -> Spliterators.iterator(spliterator);
}
}
|
MutableLong
|
java
|
grpc__grpc-java
|
testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java
|
{
"start": 4366,
"end": 5439
}
|
class ____ extends StatsRecorder {
private BlockingQueue<MetricsRecord> records;
public FakeStatsRecorder() {
rolloverRecords();
}
@Override
public MeasureMap newMeasureMap() {
return new FakeStatsRecord(this);
}
public MetricsRecord pollRecord() {
return getCurrentRecordSink().poll();
}
public MetricsRecord pollRecord(long timeout, TimeUnit unit) throws InterruptedException {
return getCurrentRecordSink().poll(timeout, unit);
}
/**
* Disconnect this tagger with the contexts it has created so far. The records from those
* contexts will not show up in {@link #pollRecord}. Useful for isolating the records between
* test cases.
*/
// This needs to be synchronized with getCurrentRecordSink() which may run concurrently.
public synchronized void rolloverRecords() {
records = new LinkedBlockingQueue<>();
}
private synchronized BlockingQueue<MetricsRecord> getCurrentRecordSink() {
return records;
}
}
public static final
|
FakeStatsRecorder
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/HttpSecurityPolicy.java
|
{
"start": 793,
"end": 1669
}
|
interface ____ {
Uni<CheckResult> checkPermission(RoutingContext request, Uni<SecurityIdentity> identity,
AuthorizationRequestContext requestContext);
/**
* If HTTP Security policy name is not null, then this policy is only called in two cases:
* - winning path-matching policy references this name in the application.properties
* - invoked Jakarta REST endpoint references this name in the {@link AuthorizationPolicy#name()} annotation attribute
* <p>
* When the name is null, this policy is considered global and is applied on every single request.
* More details and examples can be found in Quarkus documentation.
*
* @return policy name
*/
default String name() {
// null == global policy
return null;
}
/**
* The results of a permission check
*/
|
HttpSecurityPolicy
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/jcache/JMutableEntry.java
|
{
"start": 771,
"end": 841
}
|
class ____<K, V> implements MutableEntry<K, V> {
public
|
JMutableEntry
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/http/impl/Http1xOrH2ChannelConnector.java
|
{
"start": 2231,
"end": 12929
}
|
class ____ implements HttpChannelConnector {
private final HttpClientOptions options;
private final HttpClientMetrics clientMetrics;
private final NetClientInternal netClient;
public Http1xOrH2ChannelConnector(NetClientInternal netClient,
HttpClientOptions options,
HttpClientMetrics clientMetrics) {
if (!options.isKeepAlive() && options.isPipelining()) {
throw new IllegalStateException("Cannot have pipelining with no keep alive");
}
List<HttpVersion> alpnVersions = options.getAlpnVersions();
if (alpnVersions == null || alpnVersions.isEmpty()) {
if (options.getProtocolVersion() == HttpVersion.HTTP_2) {
options.setAlpnVersions(List.of(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1));
} else {
options.setAlpnVersions(List.of(options.getProtocolVersion()));
}
}
this.clientMetrics = clientMetrics;
this.options = options;
this.netClient = netClient;
}
public NetClientInternal netClient() {
return netClient;
}
public HttpClientOptions options() {
return options;
}
private Http2ClientChannelInitializer http2Initializer() {
if (options.getHttp2MultiplexImplementation()) {
return new Http2MultiplexClientChannelInitializer(
HttpUtils.fromVertxSettings(options.getInitialSettings()),
clientMetrics,
TimeUnit.SECONDS.toMillis(options.getHttp2KeepAliveTimeout()),
options.getHttp2MultiplexingLimit(),
options.isDecompressionSupported(),
options.getLogActivity());
} else {
return new Http2CodecClientChannelInitializer(options, clientMetrics);
}
}
private void connect(ContextInternal context, HttpConnectParams params, HostAndPort authority, SocketAddress server, Promise<NetSocket> promise) {
ConnectOptions connectOptions = new ConnectOptions();
connectOptions.setRemoteAddress(server);
if (authority != null) {
connectOptions.setHost(authority.host());
connectOptions.setPort(authority.port());
if (params.ssl && options.isForceSni()) {
connectOptions.setSniServerName(authority.host());
}
}
connectOptions.setSsl(params.ssl);
if (params.ssl) {
if (params.sslOptions != null) {
connectOptions.setSslOptions(params.sslOptions.copy().setUseAlpn(options.isUseAlpn()));
} else {
connectOptions.setSslOptions(new ClientSSLOptions().setHostnameVerificationAlgorithm("HTTPS"));
}
}
connectOptions.setProxyOptions(params.proxyOptions);
netClient.connectInternal(connectOptions, promise, context);
}
public Future<HttpClientConnection> wrap(ContextInternal context, HttpConnectParams params, HostAndPort authority, long maxLifetimeMillis, ClientMetrics<?, ?, ?> metrics, SocketAddress server, NetSocket so_) {
NetSocketImpl so = (NetSocketImpl) so_;
Object metric = so.metric();
PromiseInternal<HttpClientConnection> promise = context.promise();
// Remove all un-necessary handlers
ChannelPipeline pipeline = so.channelHandlerContext().pipeline();
List<ChannelHandler> removedHandlers = new ArrayList<>();
for (Map.Entry<String, ChannelHandler> stringChannelHandlerEntry : pipeline) {
ChannelHandler handler = stringChannelHandlerEntry.getValue();
if (!(handler instanceof SslHandler)) {
removedHandlers.add(handler);
}
}
removedHandlers.forEach(pipeline::remove);
//
Channel ch = so.channelHandlerContext().channel();
if (params.ssl) {
String protocol = so.applicationLayerProtocol();
if (options.isUseAlpn()) {
if ("h2".equals(protocol)) {
applyHttp2ConnectionOptions(ch.pipeline());
Http2ClientChannelInitializer http2ChannelInitializer = http2Initializer();
http2ChannelInitializer.http2Connected(context, authority, metric, maxLifetimeMillis, ch, metrics, promise);
} else {
applyHttp1xConnectionOptions(ch.pipeline());
HttpVersion fallbackProtocol = "http/1.0".equals(protocol) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
http1xConnected(fallbackProtocol, server, authority, true, context, metric, maxLifetimeMillis, ch, metrics, promise);
}
} else {
applyHttp1xConnectionOptions(ch.pipeline());
http1xConnected(options.getProtocolVersion(), server, authority, true, context, metric, maxLifetimeMillis, ch, metrics, promise);
}
} else {
if (options.getProtocolVersion() == HttpVersion.HTTP_2) {
if (options.isHttp2ClearTextUpgrade()) {
applyHttp1xConnectionOptions(pipeline);
http1xConnected(options.getProtocolVersion(), server, authority, false, context, metric, maxLifetimeMillis, ch, metrics, promise);
} else {
applyHttp2ConnectionOptions(pipeline);
Http2ClientChannelInitializer http2ChannelInitializer = http2Initializer();
http2ChannelInitializer.http2Connected(context, authority, metric, maxLifetimeMillis, ch, metrics, promise);
}
} else {
applyHttp1xConnectionOptions(pipeline);
http1xConnected(options.getProtocolVersion(), server, authority, false, context, metric, maxLifetimeMillis, ch, metrics, promise);
}
}
return promise.future();
}
public Future<HttpClientConnection> httpConnect(ContextInternal context, SocketAddress server, HostAndPort authority, HttpConnectParams params, long maxLifetimeMillis, ClientMetrics<?, ?, ?> metrics) {
if (!options.isUseAlpn() && params.ssl && this.options.getProtocolVersion() == HttpVersion.HTTP_2) {
return context.failedFuture("Must enable ALPN when using H2");
}
Promise<NetSocket> promise = context.promise();
Future<NetSocket> future = promise.future();
// We perform the compose operation before calling connect to be sure that the composition happens
// before the promise is completed by the connect operation
Future<HttpClientConnection> ret = future.compose(so -> wrap(context, params, authority, maxLifetimeMillis, metrics, server, so));
connect(context, params, authority, server, promise);
return ret;
}
private void applyHttp2ConnectionOptions(ChannelPipeline pipeline) {
int idleTimeout = options.getIdleTimeout();
int readIdleTimeout = options.getReadIdleTimeout();
int writeIdleTimeout = options.getWriteIdleTimeout();
if (idleTimeout > 0 || readIdleTimeout > 0 || writeIdleTimeout > 0) {
pipeline.addLast("idle", new IdleStateHandler(readIdleTimeout, writeIdleTimeout, idleTimeout, options.getIdleTimeoutUnit()));
}
}
private void applyHttp1xConnectionOptions(ChannelPipeline pipeline) {
int idleTimeout = options.getIdleTimeout();
int readIdleTimeout = options.getReadIdleTimeout();
int writeIdleTimeout = options.getWriteIdleTimeout();
if (idleTimeout > 0 || readIdleTimeout > 0 || writeIdleTimeout > 0) {
pipeline.addLast("idle", new IdleStateHandler(readIdleTimeout, writeIdleTimeout, idleTimeout, options.getIdleTimeoutUnit()));
}
if (options.getLogActivity()) {
pipeline.addLast("logging", new LoggingHandler(options.getActivityLogDataFormat()));
}
pipeline.addLast("codec", new HttpClientCodec(
options.getMaxInitialLineLength(),
options.getMaxHeaderSize(),
options.getMaxChunkSize(),
false,
!HttpHeadersInternal.DISABLE_HTTP_HEADERS_VALIDATION,
options.getDecoderInitialBufferSize()));
if (options.isDecompressionSupported()) {
pipeline.addLast("inflater", new HttpContentDecompressor(false));
}
}
private void http1xConnected(HttpVersion version,
SocketAddress server,
HostAndPort authority,
boolean ssl,
ContextInternal context,
Object socketMetric,
long maxLifetimeMillis, Channel ch,
ClientMetrics<?, ?, ?> metrics,
Promise<HttpClientConnection> future) {
boolean upgrade = version == HttpVersion.HTTP_2 && options.isHttp2ClearTextUpgrade();
VertxHandler<Http1xClientConnection> clientHandler = VertxHandler.create(chctx -> {
Http1xClientConnection conn = new Http1xClientConnection(upgrade ? HttpVersion.HTTP_1_1 : version, clientMetrics, options, chctx, ssl, server, authority, context, metrics, maxLifetimeMillis);
if (clientMetrics != null) {
conn.metric(socketMetric);
clientMetrics.endpointConnected(metrics);
}
return conn;
});
clientHandler.addHandler(conn -> {
if (upgrade) {
Http2ClientChannelInitializer http2ChannelInitializer = http2Initializer();
Http2UpgradeClientConnection.Http2ChannelUpgrade channelUpgrade= http2ChannelInitializer.channelUpgrade(conn, maxLifetimeMillis, metrics);
boolean preflightRequest = options.isHttp2ClearTextUpgradeWithPreflightRequest();
if (preflightRequest) {
Http2UpgradeClientConnection conn2 = new Http2UpgradeClientConnection(conn, maxLifetimeMillis, metrics, channelUpgrade);
conn2.concurrencyChangeHandler(concurrency -> {
// Ignore
});
conn2.createStream(conn.context()).onComplete(ar -> {
if (ar.succeeded()) {
HttpClientStream stream = ar.result();
stream.headHandler(resp -> {
Http2UpgradeClientConnection connection = (Http2UpgradeClientConnection) stream.connection();
HttpClientConnection unwrap = connection.unwrap();
future.tryComplete(unwrap);
});
stream.exceptionHandler(future::tryFail);
HttpRequestHead request = new HttpRequestHead("http", OPTIONS, "/", HttpHeaders.headers(), HostAndPort.authority(server.host(), server.port()),
"http://" + server + "/", null);
stream.writeHead(request, false, null, true, null, false);
} else {
future.fail(ar.cause());
}
});
} else {
future.complete(new Http2UpgradeClientConnection(conn, maxLifetimeMillis, metrics, channelUpgrade));
}
} else {
future.complete(conn);
}
});
ch.pipeline().addLast("handler", clientHandler);
}
@Override
public Future<Void> shutdown(Duration timeout) {
return netClient.shutdown(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
@Override
public Future<Void> close() {
return netClient.close();
}
}
|
Http1xOrH2ChannelConnector
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/kstream/ValueTransformerWithKey.java
|
{
"start": 1286,
"end": 2649
}
|
interface ____ stateful mapping of a value to a new value (with possible new type).
* This is a stateful record-by-record operation, i.e, {@link #transform(Object, Object)} is invoked individually for each
* record of a stream and can access and modify a state that is available beyond a single call of
* {@link #transform(Object, Object)} (cf. {@link ValueMapper} for stateless value transformation).
* Additionally, this {@code ValueTransformerWithKey} can
* {@link ProcessorContext#schedule(Duration, PunctuationType, Punctuator) schedule} a method to be
* {@link Punctuator#punctuate(long) called periodically} with the provided context.
* Note that the key is read-only and should not be modified, as this can lead to corrupt partitioning.
* If {@code ValueTransformerWithKey} is applied to a {@link KeyValue} pair record the record's key is preserved.
* <p>
* Use {@link ValueTransformerWithKeySupplier} to provide new instances of {@link ValueTransformerWithKey} to
* Kafka Stream's runtime.
* <p>
* If a record's key and value should be modified {@link Transformer} can be used.
*
* @param <K> key type
* @param <V> value type
* @param <VR> transformed value type
* @see ValueTransformer
* @see ValueTransformerWithKeySupplier
* @see KTable#transformValues(ValueTransformerWithKeySupplier, String...)
* @see Transformer
*/
public
|
for
|
java
|
apache__camel
|
dsl/camel-yaml-dsl/camel-yaml-dsl-common/src/main/java/org/apache/camel/dsl/yaml/common/exception/YamlDeserializationException.java
|
{
"start": 1004,
"end": 1678
}
|
class ____ extends MarkedYamlEngineException {
public YamlDeserializationException(String message) {
super(null, Optional.empty(), message, Optional.empty());
}
public YamlDeserializationException(Node node, String message) {
super(null, Optional.empty(), message, node.getStartMark());
}
public YamlDeserializationException(String message, Throwable cause) {
super(null, Optional.empty(), message, Optional.empty(), cause);
}
public YamlDeserializationException(Node node, String message, Throwable cause) {
super(null, Optional.empty(), message, node.getStartMark(), cause);
}
}
|
YamlDeserializationException
|
java
|
apache__camel
|
components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/InvalidAS2NameException.java
|
{
"start": 915,
"end": 2281
}
|
class ____ extends Exception {
private static final long serialVersionUID = -6284079291785073089L;
private final String name;
private final int index;
/**
* Constructs an <code>InvalidAS2NameException</code> for the specified name and index.
*
* @param name - the AS2 name that is invalid.
* @param index - the index in the <code>name</code> of the invalid character
*/
public InvalidAS2NameException(String name, int index) {
this.name = name;
this.index = index;
}
/* (non-Javadoc)
* @see java.lang.Throwable#getMessage()
*/
@Override
public String getMessage() {
char character = name.charAt(index);
String invalidChar = String.valueOf(character);
if (Character.isISOControl(character)) {
invalidChar = String.format("\\u%04x", (int) character);
}
return "Invalid character '" + invalidChar + "' at index " + index;
}
/**
* Returns the invalid AS2 name
*
* @return the invalid AS2 name
*/
public String getName() {
return name;
}
/**
* Returns the index of the invalid character in <code>name</code>
*
* @return the index of the invalid character in <code>name</code>
*/
public int getIndex() {
return index;
}
}
|
InvalidAS2NameException
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/client/OpenClientConnectionsTest.java
|
{
"start": 3191,
"end": 3567
}
|
class ____ {
static final CountDownLatch OPEN_LATCH = new CountDownLatch(2);
@OnOpen
void open(HandshakeRequest handshakeRequest) {
if (handshakeRequest.header("X-Test") != null) {
OPEN_LATCH.countDown();
}
}
}
@WebSocketClient(path = "/end", clientId = "client")
public static
|
ServerEndpoint
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/int2darrays/Int2DArrays_assertHasSameDimensionsAs_Test.java
|
{
"start": 1029,
"end": 1390
}
|
class ____ extends Int2DArraysBaseTest {
@Test
void should_delegate_to_Arrays2D() {
// GIVEN
int[][] other = new int[][] { { 0, 4 }, { 8, 12 } };
// WHEN
int2DArrays.assertHasSameDimensionsAs(info, actual, other);
// THEN
verify(arrays2d).assertHasSameDimensionsAs(info, actual, other);
}
}
|
Int2DArrays_assertHasSameDimensionsAs_Test
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/SerializationAnnotationsTest.java
|
{
"start": 1688,
"end": 1846
}
|
class ____ {
}
/**
* Class for testing an active {@link JsonSerialize#using} annotation
* for a method
*/
final static
|
ClassSerializer
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/OverrideThrowableToStringTest.java
|
{
"start": 3316,
"end": 3999
}
|
class ____ extends Throwable {
public String toString() {
return "";
}
public String getMessage() {
return "";
}
}
}\
""")
.doTest();
}
@Test
public void fixes() {
BugCheckerRefactoringTestHelper.newInstance(OverrideThrowableToString.class, getClass())
.addInputLines(
"OverrideThrowableToStringPositiveCases.java",
"""
package com.google.errorprone.bugpatterns.testdata;
/**
* @author mariasam@google.com (Maria Sam)
*/
|
OverridesBoth
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/filter/wall/IdentEqualsTest.java
|
{
"start": 784,
"end": 1232
}
|
class ____ extends TestCase {
private String sql = "select * from t where FID = 1 OR id = id";
private WallConfig config = new WallConfig();
protected void setUp() throws Exception {
}
public void testMySql() throws Exception {
assertFalse(WallUtils.isValidateMySql(sql, config));
}
public void testORACLE() throws Exception {
assertFalse(WallUtils.isValidateOracle(sql, config));
}
}
|
IdentEqualsTest
|
java
|
apache__camel
|
components/camel-hazelcast/src/generated/java/org/apache/camel/component/hazelcast/topic/HazelcastTopicComponentConfigurer.java
|
{
"start": 742,
"end": 3455
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
HazelcastTopicComponent target = (HazelcastTopicComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "hazelcastinstance":
case "hazelcastInstance": target.setHazelcastInstance(property(camelContext, com.hazelcast.core.HazelcastInstance.class, value)); return true;
case "hazelcastmode":
case "hazelcastMode": target.setHazelcastMode(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "hazelcastinstance":
case "hazelcastInstance": return com.hazelcast.core.HazelcastInstance.class;
case "hazelcastmode":
case "hazelcastMode": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
HazelcastTopicComponent target = (HazelcastTopicComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "hazelcastinstance":
case "hazelcastInstance": return target.getHazelcastInstance();
case "hazelcastmode":
case "hazelcastMode": return target.getHazelcastMode();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
|
HazelcastTopicComponentConfigurer
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/AclCommands.java
|
{
"start": 5911,
"end": 11540
}
|
class ____ extends FsCommand {
public static String NAME = SET_FACL;
public static String USAGE = "[-R] [{-b|-k} {-m|-x <acl_spec>} <path>]"
+ "|[--set <acl_spec> <path>]";
public static String DESCRIPTION = "Sets Access Control Lists (ACLs)"
+ " of files and directories.\n"
+ "Options:\n"
+ " -b :Remove all but the base ACL entries. The entries for user,"
+ " group and others are retained for compatibility with permission "
+ "bits.\n"
+ " -k :Remove the default ACL.\n"
+ " -R :Apply operations to all files and directories recursively.\n"
+ " -m :Modify ACL. New entries are added to the ACL, and existing"
+ " entries are retained.\n"
+ " -x :Remove specified ACL entries. Other ACL entries are retained.\n"
+ " --set :Fully replace the ACL, discarding all existing entries."
+ " The <acl_spec> must include entries for user, group, and others"
+ " for compatibility with permission bits. If the ACL spec contains"
+ " only access entries, then the existing default entries are retained"
+ ". If the ACL spec contains only default entries, then the existing"
+ " access entries are retained. If the ACL spec contains both access"
+ " and default entries, then both are replaced.\n"
+ " <acl_spec>: Comma separated list of ACL entries.\n"
+ " <path>: File or directory to modify.\n";
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, "b", "k", "R",
"m", "x", "-set");
List<AclEntry> aclEntries = null;
List<AclEntry> accessAclEntries = null;
@Override
protected void processOptions(LinkedList<String> args) throws IOException {
cf.parse(args);
setRecursive(cf.getOpt("R"));
// Mix of remove and modify acl flags are not allowed
boolean bothRemoveOptions = cf.getOpt("b") && cf.getOpt("k");
boolean bothModifyOptions = cf.getOpt("m") && cf.getOpt("x");
boolean oneRemoveOption = cf.getOpt("b") || cf.getOpt("k");
boolean oneModifyOption = cf.getOpt("m") || cf.getOpt("x");
boolean setOption = cf.getOpt("-set");
boolean hasExpectedOptions = cf.getOpt("b") || cf.getOpt("k") ||
cf.getOpt("m") || cf.getOpt("x") || cf.getOpt("-set");
if ((bothRemoveOptions || bothModifyOptions)
|| (oneRemoveOption && oneModifyOption)
|| (setOption && (oneRemoveOption || oneModifyOption))) {
throw new HadoopIllegalArgumentException(
"Specified flags contains both remove and modify flags");
}
// Only -m, -x and --set expects <acl_spec>
if (oneModifyOption || setOption) {
if (args.isEmpty()) {
throw new HadoopIllegalArgumentException(
"Missing arguments: <acl_spec> <path>");
}
if (args.size() < 2) {
throw new HadoopIllegalArgumentException(
"Missing either <acl_spec> or <path>");
}
aclEntries = AclEntry.parseAclSpec(args.removeFirst(), !cf.getOpt("x"));
if (aclEntries.isEmpty()) {
throw new HadoopIllegalArgumentException(
"Missing <acl_spec> entry");
}
}
if (args.isEmpty()) {
throw new HadoopIllegalArgumentException("<path> is missing");
}
if (args.size() > 1) {
throw new HadoopIllegalArgumentException("Too many arguments");
}
if (!hasExpectedOptions) {
throw new HadoopIllegalArgumentException(
"Expected one of -b, -k, -m, -x or --set options");
}
// In recursive mode, save a separate list of just the access ACL entries.
// Only directories may have a default ACL. When a recursive operation
// encounters a file under the specified path, it must pass only the
// access ACL entries.
if (isRecursive() && (oneModifyOption || setOption)) {
accessAclEntries = Lists.newArrayList();
for (AclEntry entry: aclEntries) {
if (entry.getScope() == AclEntryScope.ACCESS) {
accessAclEntries.add(entry);
}
}
}
}
@Override
protected void processPath(PathData item) throws IOException {
if (cf.getOpt("b")) {
item.fs.removeAcl(item.path);
} else if (cf.getOpt("k")) {
item.fs.removeDefaultAcl(item.path);
} else if (cf.getOpt("m")) {
List<AclEntry> entries = getAclEntries(item);
if (!entries.isEmpty()) {
item.fs.modifyAclEntries(item.path, entries);
}
} else if (cf.getOpt("x")) {
List<AclEntry> entries = getAclEntries(item);
if (!entries.isEmpty()) {
item.fs.removeAclEntries(item.path, entries);
}
} else if (cf.getOpt("-set")) {
List<AclEntry> entries = getAclEntries(item);
if (!entries.isEmpty()) {
item.fs.setAcl(item.path, entries);
}
}
}
/**
* Returns the ACL entries to use in the API call for the given path. For a
* recursive operation, returns all specified ACL entries if the item is a
* directory or just the access ACL entries if the item is a file. For a
* non-recursive operation, returns all specified ACL entries.
*
* @param item PathData path to check
* @return List<AclEntry> ACL entries to use in the API call
*/
private List<AclEntry> getAclEntries(PathData item) {
if (isRecursive()) {
return item.stat.isDirectory() ? aclEntries : accessAclEntries;
} else {
return aclEntries;
}
}
}
}
|
SetfaclCommand
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/functional/InterfaceTest.java
|
{
"start": 1575,
"end": 1797
}
|
class ____ implements TestObjectInterface {
@SuppressWarnings("unused")
private String someStringValue;
private TestObject(String value) {
this.someStringValue = value;
}
}
private static
|
TestObject
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/AbstractMapWritable.java
|
{
"start": 1558,
"end": 1777
}
|
class ____ of being static.
*
* Class ids range from 1 to 127 so there can be at most 127 distinct classes
* in any specific map instance.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public abstract
|
instead
|
java
|
netty__netty
|
handler/src/test/java/io/netty/handler/ssl/MockAlternativeKeyProvider.java
|
{
"start": 9423,
"end": 9669
}
|
class ____ extends MockSignature {
public MockSha1WithEcdsaSignature() throws NoSuchAlgorithmException, NoSuchProviderException {
super("SHA1withECDSA", "SunEC");
}
}
public static final
|
MockSha1WithEcdsaSignature
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2TruncateTest2.java
|
{
"start": 1037,
"end": 2746
}
|
class ____ extends DB2Test {
public void test_0() throws Exception {
String sql = "TRUNCATE TABLE INVENTORY IGNORE DELETE TRIGGERS DROP STORAGE IMMEDIATE";
DB2StatementParser parser = new DB2StatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor();
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(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("INVENTORY")));
// assertTrue(visitor.getColumns().contains(new Column("A", "F_0201")));
// assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name")));
// assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name")));
assertEquals("TRUNCATE TABLE INVENTORY DROP STORAGE IGNORE DELETE TRIGGERS IMMEDIATE", //
SQLUtils.toSQLString(stmt, JdbcConstants.DB2));
assertEquals("truncate table INVENTORY drop storage ignore delete triggers immediate", //
SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION));
}
}
|
DB2TruncateTest2
|
java
|
spring-projects__spring-boot
|
module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/LdapProperties.java
|
{
"start": 1222,
"end": 3812
}
|
class ____ {
private static final int DEFAULT_PORT = 389;
/**
* LDAP URLs of the server.
*/
private String @Nullable [] urls;
/**
* Base suffix from which all operations should originate.
*/
private @Nullable String base;
/**
* Login username of the server.
*/
private @Nullable String username;
/**
* Login password of the server.
*/
private @Nullable String password;
/**
* Whether read-only operations should use an anonymous environment. Disabled by
* default unless a username is set.
*/
private @Nullable Boolean anonymousReadOnly;
/**
* Specify how referrals encountered by the service provider are to be processed. If
* not specified, the default is determined by the provider.
*/
private @Nullable Referral referral;
/**
* LDAP specification settings.
*/
private final Map<String, String> baseEnvironment = new HashMap<>();
private final Template template = new Template();
public String @Nullable [] getUrls() {
return this.urls;
}
public void setUrls(String @Nullable [] urls) {
this.urls = urls;
}
public @Nullable String getBase() {
return this.base;
}
public void setBase(@Nullable String base) {
this.base = base;
}
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable Boolean getAnonymousReadOnly() {
return this.anonymousReadOnly;
}
public void setAnonymousReadOnly(@Nullable Boolean anonymousReadOnly) {
this.anonymousReadOnly = anonymousReadOnly;
}
public @Nullable Referral getReferral() {
return this.referral;
}
public void setReferral(@Nullable Referral referral) {
this.referral = referral;
}
public Map<String, String> getBaseEnvironment() {
return this.baseEnvironment;
}
public Template getTemplate() {
return this.template;
}
public String[] determineUrls(Environment environment) {
if (ObjectUtils.isEmpty(this.urls)) {
return new String[] { "ldap://localhost:" + determinePort(environment) };
}
return this.urls;
}
private int determinePort(Environment environment) {
Assert.notNull(environment, "'environment' must not be null");
String localPort = environment.getProperty("local.ldap.port");
if (localPort != null) {
return Integer.parseInt(localPort);
}
return DEFAULT_PORT;
}
/**
* {@link LdapTemplate settings}.
*/
public static
|
LdapProperties
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldContainEntries.java
|
{
"start": 1008,
"end": 5257
}
|
class ____ extends BasicErrorMessageFactory {
public static <K, V> ErrorMessageFactory shouldContainEntries(Map<? extends K, ? extends V> actual,
Entry<? extends K, ? extends V>[] expectedEntries,
Set<Entry<? extends K, ? extends V>> entriesWithWrongValue,
Set<Entry<? extends K, ? extends V>> entriesWithKeyNotFound,
Representation representation) {
if (entriesWithWrongValue.isEmpty())
return new ShouldContainEntries(actual, expectedEntries, getKeys(entriesWithKeyNotFound));
if (entriesWithKeyNotFound.isEmpty())
return new ShouldContainEntries(actual, expectedEntries,
buildValueDifferences(actual, entriesWithWrongValue, representation));
// mix of missing keys and keys with different values
return new ShouldContainEntries(actual, expectedEntries, getKeys(entriesWithKeyNotFound),
buildValueDifferences(actual, entriesWithWrongValue, representation));
}
private static <K, V> List<String> buildValueDifferences(Map<? extends K, ? extends V> actual,
Set<Entry<? extends K, ? extends V>> entriesWithWrongValues,
Representation representation) {
return entriesWithWrongValues.stream()
.map(entryWithWrongValue -> valueDifference(actual, entryWithWrongValue, representation))
.toList();
}
private static <K, V> List<K> getKeys(Set<Entry<? extends K, ? extends V>> entries) {
return entries.stream()
.map(Entry::getKey)
.collect(toList());
}
private static <K, V> String valueDifference(Map<? extends K, ? extends V> actual,
Entry<? extends K, ? extends V> entryWithWrongValue,
Representation representation) {
K key = entryWithWrongValue.getKey();
MapEntry<K, ? extends V> actualEntry = entry(key, actual.get(key));
V expectedValue = entryWithWrongValue.getValue();
return escapePercent("%s (expected: %s)".formatted(representation.toStringOf(actualEntry),
representation.toStringOf(expectedValue)));
}
private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual,
Entry<? extends K, ? extends V>[] expectedEntries,
Iterable<? extends K> keysNotFound) {
super("%nExpecting map:%n" +
" %s%n" +
"to contain entries:%n" +
" %s%n" +
"but could not find the following map keys:%n" +
" %s",
actual, expectedEntries, keysNotFound);
}
private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual,
Entry<? extends K, ? extends V>[] expectedEntries,
List<String> valueDifferences) {
super("%nExpecting map:%n" +
" %s%n" +
"to contain entries:%n" +
" %s%n" +
"but the following map entries had different values:%n" +
" " + valueDifferences,
actual, expectedEntries, valueDifferences);
}
private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual,
Entry<? extends K, ? extends V>[] expectedEntries,
Iterable<? extends K> keysNotFound,
List<String> valueDifferences) {
super("%nExpecting map:%n" +
" %s%n" +
"to contain entries:%n" +
" %s%n" +
"but could not find the following map keys:%n" +
" %s%n" +
"and the following map entries had different values:%n" +
" " + valueDifferences,
actual, expectedEntries, keysNotFound);
}
}
|
ShouldContainEntries
|
java
|
elastic__elasticsearch
|
server/src/internalClusterTest/java/org/elasticsearch/search/retriever/MinimalCompoundRetrieverIT.java
|
{
"start": 1703,
"end": 6533
}
|
class ____ extends AbstractMultiClustersTestCase {
// CrossClusterSearchIT
private static final String REMOTE_CLUSTER = "cluster_a";
@Override
protected List<String> remoteClusterAlias() {
return List.of(REMOTE_CLUSTER);
}
@Override
protected Map<String, Boolean> skipUnavailableForRemoteClusters() {
return Map.of(REMOTE_CLUSTER, randomBoolean());
}
@Override
protected boolean reuseClusters() {
return false;
}
public void testSimpleSearch() throws ExecutionException, InterruptedException {
RetrieverBuilder compoundRetriever = new CompoundRetriever(Collections.emptyList());
Map<String, Object> testClusterInfo = setupTwoClusters();
String localIndex = (String) testClusterInfo.get("local.index");
String remoteIndex = (String) testClusterInfo.get("remote.index");
SearchRequest searchRequest = new SearchRequest(localIndex, REMOTE_CLUSTER + ":" + remoteIndex);
searchRequest.source(new SearchSourceBuilder().retriever(compoundRetriever));
assertResponse(client(LOCAL_CLUSTER).search(searchRequest), response -> {
assertNotNull(response);
SearchResponse.Clusters clusters = response.getClusters();
assertFalse("search cluster results should NOT be marked as partial", clusters.hasPartialResults());
assertThat(clusters.getTotal(), equalTo(2));
assertThat(clusters.getClusterStateCount(SearchResponse.Cluster.Status.SUCCESSFUL), equalTo(2));
assertThat(clusters.getClusterStateCount(SearchResponse.Cluster.Status.SKIPPED), equalTo(0));
assertThat(clusters.getClusterStateCount(SearchResponse.Cluster.Status.RUNNING), equalTo(0));
assertThat(clusters.getClusterStateCount(SearchResponse.Cluster.Status.PARTIAL), equalTo(0));
assertThat(clusters.getClusterStateCount(SearchResponse.Cluster.Status.FAILED), equalTo(0));
assertThat(response.getHits().getTotalHits().value(), equalTo(testClusterInfo.get("total_docs")));
});
}
private Map<String, Object> setupTwoClusters() {
int totalDocs = 0;
String localIndex = "demo";
int numShardsLocal = randomIntBetween(2, 10);
Settings localSettings = indexSettings(numShardsLocal, randomIntBetween(0, 1)).build();
assertAcked(
client(LOCAL_CLUSTER).admin()
.indices()
.prepareCreate(localIndex)
.setSettings(localSettings)
.setMapping("some_field", "type=keyword")
);
totalDocs += indexDocs(client(LOCAL_CLUSTER), localIndex);
String remoteIndex = "prod";
int numShardsRemote = randomIntBetween(2, 10);
final InternalTestCluster remoteCluster = cluster(REMOTE_CLUSTER);
remoteCluster.ensureAtLeastNumDataNodes(randomIntBetween(1, 3));
assertAcked(
client(REMOTE_CLUSTER).admin()
.indices()
.prepareCreate(remoteIndex)
.setSettings(indexSettings(numShardsRemote, randomIntBetween(0, 1)))
.setMapping("some_field", "type=keyword")
);
assertFalse(
client(REMOTE_CLUSTER).admin()
.cluster()
.prepareHealth(TEST_REQUEST_TIMEOUT, remoteIndex)
.setWaitForYellowStatus()
.setTimeout(TimeValue.timeValueSeconds(10))
.get()
.isTimedOut()
);
totalDocs += indexDocs(client(REMOTE_CLUSTER), remoteIndex);
String skipUnavailableKey = Strings.format("cluster.remote.%s.skip_unavailable", REMOTE_CLUSTER);
Setting<?> skipUnavailableSetting = cluster(REMOTE_CLUSTER).clusterService().getClusterSettings().get(skipUnavailableKey);
boolean skipUnavailable = (boolean) cluster(RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY).clusterService()
.getClusterSettings()
.get(skipUnavailableSetting);
Map<String, Object> clusterInfo = new HashMap<>();
clusterInfo.put("local.num_shards", numShardsLocal);
clusterInfo.put("local.index", localIndex);
clusterInfo.put("remote.num_shards", numShardsRemote);
clusterInfo.put("remote.index", remoteIndex);
clusterInfo.put("remote.skip_unavailable", skipUnavailable);
clusterInfo.put("total_docs", (long) totalDocs);
return clusterInfo;
}
private int indexDocs(Client client, String index) {
int numDocs = between(500, 1200);
for (int i = 0; i < numDocs; i++) {
client.prepareIndex(index).setSource("some_field", i).get();
}
client.admin().indices().prepareRefresh(index).get();
return numDocs;
}
public static
|
MinimalCompoundRetrieverIT
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/action/RestUpdateConnectorConfigurationActionTests.java
|
{
"start": 716,
"end": 1537
}
|
class ____ extends ESTestCase {
private RestUpdateConnectorConfigurationAction action;
@Override
public void setUp() throws Exception {
super.setUp();
action = new RestUpdateConnectorConfigurationAction();
}
public void testPrepareRequest_emptyPayload_badRequestError() {
RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.PUT)
.withPath("/_connector/123/_configuration")
.build();
final ElasticsearchParseException e = expectThrows(
ElasticsearchParseException.class,
() -> action.prepareRequest(request, mock(NodeClient.class))
);
assertThat(e, hasToString(containsString("request body is required")));
}
}
|
RestUpdateConnectorConfigurationActionTests
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListGroovy.java
|
{
"start": 6280,
"end": 6744
}
|
class ____ implements Cloneable {
String pid;
String name;
int compiledCounter;
int preloaddCounter;
int classesSize;
long time;
long last;
List<String> compiledClasses = new ArrayList<>();
Row copy() {
try {
return (Row) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
}
|
Row
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/ProducerFieldMultipleScopesTest.java
|
{
"start": 583,
"end": 975
}
|
class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder().beanClasses(Alpha.class).shouldFail().build();
@Test
public void testFailure() {
Throwable error = container.getFailure();
assertNotNull(error);
assertTrue(error instanceof DefinitionException);
}
@Dependent
static
|
ProducerFieldMultipleScopesTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/AndroidInjectionBeforeSuperTest.java
|
{
"start": 2667,
"end": 3309
}
|
interface ____ {}\
""");
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"AndroidInjectionBeforeSuperPositiveCases.java",
"""
package com.google.errorprone.bugpatterns.inject.dagger.testdata;
import android.app.Activity;
import android.app.Fragment;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import dagger.android.AndroidInjection;
final
|
IBinder
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/JdbcTypeRegistrationAnnotation.java
|
{
"start": 478,
"end": 2008
}
|
class ____ implements JdbcTypeRegistration {
private java.lang.Class<? extends org.hibernate.type.descriptor.jdbc.JdbcType> value;
private int registrationCode;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public JdbcTypeRegistrationAnnotation(ModelsContext modelContext) {
this.registrationCode = -2147483648;
}
/**
* Used in creating annotation instances from JDK variant
*/
public JdbcTypeRegistrationAnnotation(JdbcTypeRegistration annotation, ModelsContext modelContext) {
this.value = annotation.value();
this.registrationCode = annotation.registrationCode();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public JdbcTypeRegistrationAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.value = (Class<? extends org.hibernate.type.descriptor.jdbc.JdbcType>) attributeValues.get( "value" );
this.registrationCode = (int) attributeValues.get( "registrationCode" );
}
@Override
public Class<? extends Annotation> annotationType() {
return JdbcTypeRegistration.class;
}
@Override
public java.lang.Class<? extends org.hibernate.type.descriptor.jdbc.JdbcType> value() {
return value;
}
public void value(java.lang.Class<? extends org.hibernate.type.descriptor.jdbc.JdbcType> value) {
this.value = value;
}
@Override
public int registrationCode() {
return registrationCode;
}
public void registrationCode(int value) {
this.registrationCode = value;
}
}
|
JdbcTypeRegistrationAnnotation
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/admin/indices/template/delete/TransportDeleteComponentTemplateAction.java
|
{
"start": 4084,
"end": 5364
}
|
class ____ extends MasterNodeRequest<Request> {
private final String[] names;
public Request(StreamInput in) throws IOException {
super(in);
names = in.readStringArray();
}
/**
* Constructs a new delete index request for the specified name.
*/
public Request(String... names) {
super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT);
this.names = Objects.requireNonNull(names, "component templates to delete must not be null");
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (Arrays.stream(names).anyMatch(Strings::hasLength) == false) {
validationException = addValidationError("no component template names specified", validationException);
}
return validationException;
}
/**
* The index template names to delete.
*/
public String[] names() {
return names;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(names);
}
}
}
|
Request
|
java
|
google__dagger
|
hilt-android/main/java/dagger/hilt/android/internal/managers/ComponentSupplier.java
|
{
"start": 916,
"end": 964
}
|
interface ____ {
Object get();
}
|
ComponentSupplier
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/ExceptionHandlingTests.java
|
{
"start": 12676,
"end": 13081
}
|
class ____ {
TestCaseWithInvalidConstructorAndThrowingAfterAllCallbackAndPerClassLifecycle() {
throw new IllegalStateException("constructor");
}
@Test
void test() {
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
@ExtendWith(ThrowingBeforeAllCallback.class)
@ExtendWith(ThrowingAfterAllCallback.class)
static
|
TestCaseWithInvalidConstructorAndThrowingAfterAllCallbackAndPerClassLifecycle
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaDropTest.java
|
{
"start": 3660,
"end": 3753
}
|
class ____ {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Long id;
}
}
|
MyEntity
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/retry/UnreliableInterface.java
|
{
"start": 1651,
"end": 2050
}
|
class ____ extends Exception {
private static final long serialVersionUID = 1L;
private String identifier;
public UnreliableException() {
// no body
}
public UnreliableException(String identifier) {
this.identifier = identifier;
}
@Override
public String getMessage() {
return identifier;
}
}
public static
|
UnreliableException
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/bytecode/internal/bytebuddy/ProxyFactoryFactoryImpl.java
|
{
"start": 491,
"end": 1341
}
|
class ____ implements ProxyFactoryFactory {
private final ByteBuddyState byteBuddyState;
private final ByteBuddyProxyHelper byteBuddyProxyHelper;
public ProxyFactoryFactoryImpl(ByteBuddyState byteBuddyState, ByteBuddyProxyHelper byteBuddyProxyHelper) {
this.byteBuddyState = byteBuddyState;
this.byteBuddyProxyHelper = byteBuddyProxyHelper;
}
@Override
public ProxyFactory buildProxyFactory(SessionFactoryImplementor sessionFactory) {
return new ByteBuddyProxyFactory( byteBuddyProxyHelper );
}
public BasicProxyFactory buildBasicProxyFactory(Class superClassOrInterface) {
if ( superClassOrInterface.isInterface() ) {
return new BasicProxyFactoryImpl( null, superClassOrInterface, byteBuddyState );
}
else {
return new BasicProxyFactoryImpl( superClassOrInterface, null, byteBuddyState );
}
}
}
|
ProxyFactoryFactoryImpl
|
java
|
spring-projects__spring-framework
|
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveIndexAccessor.java
|
{
"start": 2090,
"end": 3572
}
|
interface ____ compilation to succeed.
*
* <h3>Example</h3>
*
* <p>The {@code FruitMap} class (the {@code targetType}) represents a structure
* that is indexed via the {@code Color} enum (the {@code indexType}). The name
* of the read-method is {@code "getFruit"}, and that method returns a
* {@code String} (the {@code indexedValueType}). The name of the write-method
* is {@code "setFruit"}, and that method accepts a {@code Color} enum (the
* {@code indexType}) and a {@code String} (the {@code indexedValueType} which
* must match the return type of the read-method).
*
* <p>A read-only {@code IndexAccessor} for {@code FruitMap} can be created via
* {@code new ReflectiveIndexAccessor(FruitMap.class, Color.class, "getFruit")}.
* With that accessor registered and a {@code FruitMap} registered as a variable
* named {@code #fruitMap}, the SpEL expression {@code #fruitMap[T(example.Color).RED]}
* will evaluate to {@code "cherry"}.
*
* <p>A read-write {@code IndexAccessor} for {@code FruitMap} can be created via
* {@code new ReflectiveIndexAccessor(FruitMap.class, Color.class, "getFruit", "setFruit")}.
* With that accessor registered and a {@code FruitMap} registered as a variable
* named {@code #fruitMap}, the SpEL expression
* {@code #fruitMap[T(example.Color).RED] = 'strawberry'} can be used to change
* the fruit mapping for the color red from {@code "cherry"} to {@code "strawberry"}.
*
* <pre class="code">
* package example;
*
* public
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/googlevertexai/rerank/GoogleVertexAiRerankTaskSettings.java
|
{
"start": 990,
"end": 3742
}
|
class ____ implements TaskSettings {
public static final String NAME = "google_vertex_ai_rerank_task_settings";
public static final String TOP_N = "top_n";
public static GoogleVertexAiRerankTaskSettings fromMap(Map<String, Object> map) {
ValidationException validationException = new ValidationException();
Integer topN = extractOptionalPositiveInteger(map, TOP_N, ModelConfigurations.TASK_SETTINGS, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new GoogleVertexAiRerankTaskSettings(topN);
}
public static GoogleVertexAiRerankTaskSettings of(
GoogleVertexAiRerankTaskSettings originalSettings,
GoogleVertexAiRerankRequestTaskSettings requestSettings
) {
var topN = requestSettings.topN() == null ? originalSettings.topN() : requestSettings.topN();
return new GoogleVertexAiRerankTaskSettings(topN);
}
private final Integer topN;
public GoogleVertexAiRerankTaskSettings(@Nullable Integer topN) {
this.topN = topN;
}
public GoogleVertexAiRerankTaskSettings(StreamInput in) throws IOException {
this.topN = in.readOptionalVInt();
}
@Override
public boolean isEmpty() {
return topN == null;
}
public Integer topN() {
return topN;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_15_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalVInt(topN);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (topN != null) {
builder.field(TOP_N, topN);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
GoogleVertexAiRerankTaskSettings that = (GoogleVertexAiRerankTaskSettings) object;
return Objects.equals(topN, that.topN);
}
@Override
public int hashCode() {
return Objects.hash(topN);
}
@Override
public TaskSettings updatedTaskSettings(Map<String, Object> newSettings) {
GoogleVertexAiRerankRequestTaskSettings requestSettings = GoogleVertexAiRerankRequestTaskSettings.fromMap(
new HashMap<>(newSettings)
);
return of(this, requestSettings);
}
}
|
GoogleVertexAiRerankTaskSettings
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorMultipleDefinitionTest.java
|
{
"start": 1854,
"end": 1985
}
|
class ____ {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "table-generator")
public long id;
}
}
|
TestEntity2
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java
|
{
"start": 16740,
"end": 17160
}
|
enum ____ implements Function<io.reactivex.Observable<?>, Flux<?>> {
INSTANCE;
@Override
public Flux<?> apply(io.reactivex.Observable<?> source) {
return Flux.from(source.toFlowable(BackpressureStrategy.BUFFER));
}
}
/**
* An adapter {@link Function} to adopt a {@link Publisher} to {@link io.reactivex.Flowable}.
*/
public
|
RxJava2ObservableToFluxAdapter
|
java
|
spring-projects__spring-boot
|
module/spring-boot-http-client/src/test/java/org/springframework/boot/http/client/HttpClientSettingsTests.java
|
{
"start": 960,
"end": 4187
}
|
class ____ {
private static final Duration ONE_SECOND = Duration.ofSeconds(1);
private static final Duration TWO_SECONDS = Duration.ofSeconds(2);
@Test
void defaults() {
HttpClientSettings settings = HttpClientSettings.defaults();
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isNull();
}
@Test
void createWithNulls() {
HttpClientSettings settings = new HttpClientSettings(null, null, null, null);
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isNull();
}
@Test
void withConnectTimeoutReturnsInstanceWithUpdatedConnectionTimeout() {
HttpClientSettings settings = HttpClientSettings.defaults().withConnectTimeout(ONE_SECOND);
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isEqualTo(ONE_SECOND);
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isNull();
}
@Test
void withReadTimeoutReturnsInstanceWithUpdatedReadTimeout() {
HttpClientSettings settings = HttpClientSettings.defaults().withReadTimeout(ONE_SECOND);
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isEqualTo(ONE_SECOND);
assertThat(settings.sslBundle()).isNull();
}
@Test
void withSslBundleReturnsInstanceWithUpdatedSslBundle() {
SslBundle sslBundle = mock(SslBundle.class);
HttpClientSettings settings = HttpClientSettings.defaults().withSslBundle(sslBundle);
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isSameAs(sslBundle);
}
@Test
void withRedirectsReturnsInstanceWithUpdatedRedirect() {
HttpClientSettings settings = HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW);
assertThat(settings.redirects()).isEqualTo(HttpRedirects.DONT_FOLLOW);
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isNull();
}
@Test
void orElseReturnsNewInstanceWithUpdatedValues() {
SslBundle sslBundle = mock(SslBundle.class);
HttpClientSettings settings = new HttpClientSettings(null, ONE_SECOND, null, null)
.orElse(new HttpClientSettings(HttpRedirects.FOLLOW_WHEN_POSSIBLE, TWO_SECONDS, TWO_SECONDS, sslBundle));
assertThat(settings.redirects()).isEqualTo(HttpRedirects.FOLLOW_WHEN_POSSIBLE);
assertThat(settings.connectTimeout()).isEqualTo(ONE_SECOND);
assertThat(settings.readTimeout()).isEqualTo(TWO_SECONDS);
assertThat(settings.sslBundle()).isEqualTo(sslBundle);
}
@Test
void ofSslBundleCreatesNewSettings() {
SslBundle sslBundle = mock(SslBundle.class);
HttpClientSettings settings = HttpClientSettings.ofSslBundle(sslBundle);
assertThat(settings.redirects()).isNull();
assertThat(settings.connectTimeout()).isNull();
assertThat(settings.readTimeout()).isNull();
assertThat(settings.sslBundle()).isSameAs(sslBundle);
}
}
|
HttpClientSettingsTests
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/util/comparator/ComparatorsTests.java
|
{
"start": 878,
"end": 2336
}
|
class ____ {
@Test
void nullsLow() {
assertThat(Comparators.nullsLow().compare("boo", "boo")).isZero();
assertThat(Comparators.nullsLow().compare(null, null)).isZero();
assertThat(Comparators.nullsLow().compare(null, "boo")).isNegative();
assertThat(Comparators.nullsLow().compare("boo", null)).isPositive();
}
@Test
void nullsLowWithExplicitComparator() {
assertThat(Comparators.nullsLow(String::compareTo).compare("boo", "boo")).isZero();
assertThat(Comparators.nullsLow(String::compareTo).compare(null, null)).isZero();
assertThat(Comparators.nullsLow(String::compareTo).compare(null, "boo")).isNegative();
assertThat(Comparators.nullsLow(String::compareTo).compare("boo", null)).isPositive();
}
@Test
void nullsHigh() {
assertThat(Comparators.nullsHigh().compare("boo", "boo")).isZero();
assertThat(Comparators.nullsHigh().compare(null, null)).isZero();
assertThat(Comparators.nullsHigh().compare(null, "boo")).isPositive();
assertThat(Comparators.nullsHigh().compare("boo", null)).isNegative();
}
@Test
void nullsHighWithExplicitComparator() {
assertThat(Comparators.nullsHigh(String::compareTo).compare("boo", "boo")).isZero();
assertThat(Comparators.nullsHigh(String::compareTo).compare(null, null)).isZero();
assertThat(Comparators.nullsHigh(String::compareTo).compare(null, "boo")).isPositive();
assertThat(Comparators.nullsHigh(String::compareTo).compare("boo", null)).isNegative();
}
}
|
ComparatorsTests
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlan.java
|
{
"start": 1347,
"end": 6268
}
|
class ____ {
private final Map<MavenProject, Map<String, BuildStep>> plan = new LinkedHashMap<>();
private final Map<MavenProject, List<MavenProject>> projects;
private final Map<String, String> aliases = new HashMap<>();
private volatile Set<String> duplicateIds;
private volatile List<BuildStep> sortedNodes;
BuildPlan() {
this.projects = null;
}
public BuildPlan(Map<MavenProject, List<MavenProject>> projects) {
this.projects = projects;
}
public Map<MavenProject, List<MavenProject>> getAllProjects() {
return projects;
}
public Map<String, String> aliases() {
return aliases;
}
public Stream<MavenProject> projects() {
return plan.keySet().stream();
}
public void addProject(MavenProject project, Map<String, BuildStep> steps) {
plan.put(project, steps);
}
public void addStep(MavenProject project, String name, BuildStep step) {
plan.get(project).put(name, step);
}
public Stream<BuildStep> allSteps() {
return plan.values().stream().flatMap(m -> m.values().stream());
}
public Stream<BuildStep> steps(MavenProject project) {
return Optional.ofNullable(plan.get(project))
.map(m -> m.values().stream())
.orElse(Stream.empty());
}
public Optional<BuildStep> step(MavenProject project, String name) {
return Optional.ofNullable(plan.get(project)).map(m -> m.get(name));
}
public BuildStep requiredStep(MavenProject project, String name) {
return step(project, name).orElseThrow(() -> new NoSuchElementException("Step " + name + " not found"));
}
// add a follow-up plan to this one
public void then(BuildPlan step) {
step.plan.forEach((k, v) -> plan.merge(k, v, this::merge));
aliases.putAll(step.aliases);
}
private Map<String, BuildStep> merge(Map<String, BuildStep> org, Map<String, BuildStep> add) {
// all new phases should be added after the existing ones
List<BuildStep> lasts =
org.values().stream().filter(b -> b.successors.isEmpty()).toList();
List<BuildStep> firsts =
add.values().stream().filter(b -> b.predecessors.isEmpty()).toList();
firsts.stream()
.filter(addNode -> !org.containsKey(addNode.name))
.forEach(addNode -> lasts.forEach(orgNode -> addNode.executeAfter(orgNode)));
add.forEach((name, node) -> org.merge(name, node, this::merge));
return org;
}
private BuildStep merge(BuildStep node1, BuildStep node2) {
node1.predecessors.addAll(node2.predecessors);
node1.successors.addAll(node2.successors);
node2.mojos.forEach((k, v) -> node1.mojos.merge(k, v, this::mergeMojos));
return node1;
}
private Map<String, MojoExecution> mergeMojos(Map<String, MojoExecution> l1, Map<String, MojoExecution> l2) {
l2.forEach(l1::putIfAbsent);
return l1;
}
// gather artifactIds which are not unique so that the respective thread names can be extended with the groupId
public Set<String> duplicateIds() {
if (duplicateIds == null) {
synchronized (this) {
if (duplicateIds == null) {
duplicateIds = projects()
.map(MavenProject::getArtifactId)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(p -> p.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
}
}
return duplicateIds;
}
public List<BuildStep> sortedNodes() {
if (sortedNodes == null) {
synchronized (this) {
if (sortedNodes == null) {
List<BuildStep> sortedNodes = new ArrayList<>();
Set<BuildStep> visited = new HashSet<>();
// Visit each unvisited node
allSteps().forEach(node -> visitNode(node, visited, sortedNodes));
// Reverse the sorted nodes to get the correct order
Collections.reverse(sortedNodes);
this.sortedNodes = sortedNodes;
}
}
}
return sortedNodes;
}
// Helper method to visit a node
private static void visitNode(BuildStep node, Set<BuildStep> visited, List<BuildStep> sortedNodes) {
if (visited.add(node)) {
// For each successor of the current node, visit unvisited successors
node.successors.forEach(successor -> visitNode(successor, visited, sortedNodes));
sortedNodes.add(node);
}
}
}
|
BuildPlan
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/federation/GraphQLFederationTracingTest.java
|
{
"start": 1942,
"end": 2050
}
|
class ____ {
@Query
public String getFoo() {
return "foo";
}
}
}
|
FooApi
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedForDefaultNotUsing.java
|
{
"start": 1539,
"end": 9118
}
|
class ____ extends AbstractModifiedFlagsEntityTest {
private static final int entityId = 1;
private static final int refEntityId = 1;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
PartialModifiedFlagsEntity entity = new PartialModifiedFlagsEntity( entityId );
// Revision 1
em.getTransaction().begin();
em.persist( entity );
em.getTransaction().commit();
// Revision 2
em.getTransaction().begin();
entity.setData( "data1" );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 3
em.getTransaction().begin();
entity.setComp1( new Component1( "str1", "str2" ) );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 4
em.getTransaction().begin();
entity.setComp2( new Component2( "str1", "str2" ) );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 5
em.getTransaction().begin();
WithModifiedFlagReferencingEntity withModifiedFlagReferencingEntity = new WithModifiedFlagReferencingEntity(
refEntityId, "first" );
withModifiedFlagReferencingEntity.setReference( entity );
em.persist( withModifiedFlagReferencingEntity );
em.getTransaction().commit();
// Revision 6
em.getTransaction().begin();
withModifiedFlagReferencingEntity = em.find( WithModifiedFlagReferencingEntity.class, refEntityId );
withModifiedFlagReferencingEntity.setReference( null );
withModifiedFlagReferencingEntity.setSecondReference( entity );
em.merge( withModifiedFlagReferencingEntity );
em.getTransaction().commit();
// Revision 7
em.getTransaction().begin();
entity.getStringSet().add( "firstElement" );
entity.getStringSet().add( "secondElement" );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 8
em.getTransaction().begin();
entity.getStringSet().remove( "secondElement" );
entity.getStringMap().put( "someKey", "someValue" );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 9 - main entity doesn't change
em.getTransaction().begin();
StrTestEntity strTestEntity = new StrTestEntity( "first" );
em.persist( strTestEntity );
em.getTransaction().commit();
// Revision 10
em.getTransaction().begin();
entity.getEntitiesSet().add( strTestEntity );
entity = em.merge( entity );
em.getTransaction().commit();
// Revision 11
em.getTransaction().begin();
entity.getEntitiesSet().remove( strTestEntity );
entity.getEntitiesMap().put( "someKey", strTestEntity );
em.merge( entity );
em.getTransaction().commit();
// Revision 12 - main entity doesn't change
em.getTransaction().begin();
strTestEntity.setStr( "second" );
em.merge( strTestEntity );
em.getTransaction().commit();
} );
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals( Arrays.asList( 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ),
auditReader.getRevisions( PartialModifiedFlagsEntity.class, entityId ) );
} );
}
@Test
public void testHasChangedData(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId, "data" );
assertEquals( 1, list.size() );
assertEquals( makeList( 2 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedComp1(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId, "comp1" );
assertEquals( 1, list.size() );
assertEquals( makeList( 3 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedComp2(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertThrows( IllegalArgumentException.class,
() -> queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"comp2" ) );
} );
}
@Test
public void testHasChangedReferencing(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"referencing" );
assertEquals( 2, list.size() );
assertEquals( makeList( 5, 6 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedReferencing2(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertThrows( IllegalArgumentException.class,
() -> queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"referencing2" ) );
} );
}
@Test
public void testHasChangedStringSet(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"stringSet" );
assertEquals( 3, list.size() );
assertEquals( makeList( 1, 7, 8 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedStringMap(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"stringMap" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 8 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedStringSetAndMap(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"stringSet", "stringMap" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 8 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedEntitiesSet(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"entitiesSet" );
assertEquals( 3, list.size() );
assertEquals( makeList( 1, 10, 11 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedEntitiesMap(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"entitiesMap" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 11 ), extractRevisionNumbers( list ) );
} );
}
@Test
public void testHasChangedEntitiesSetAndMap(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
List list = queryForPropertyHasChanged( auditReader, PartialModifiedFlagsEntity.class, entityId,
"entitiesSet", "entitiesMap" );
assertEquals( 2, list.size() );
assertEquals( makeList( 1, 11 ), extractRevisionNumbers( list ) );
} );
}
}
|
HasChangedForDefaultNotUsing
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/EnumNamingStrategies.java
|
{
"start": 15023,
"end": 15603
}
|
enum ____ in the typical upper
* snake case format to upper camel case format.
* This implementation first normalizes to lower camel case using (see {@link LowerCamelCaseStrategy} for details)
* and then uses {@link PropertyNamingStrategies.KebabCaseStrategy} to finish converting the name.
* <p>
* WARNING: Naming conversion conflicts caused by underscore usage should be handled by client.
* e.g. Both <code>PEANUT_BUTTER</code>, <code>PEANUT__BUTTER</code> are converted into "peanut-butter".
* And "peanut-butter" will be deserialized into
|
names
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/JUnit4EmptyMethods.java
|
{
"start": 2764,
"end": 3166
}
|
class ____ and java.lang.Object
return Description.NO_MATCH;
}
// if it's an empty JUnit method, delete it
if (method.getBody() != null
&& method.getBody().getStatements().isEmpty()
&& JUNIT_METHODS.matches(method, state)
&& !containsComments(method, state)) {
return describeMatch(method, delete(method));
}
return Description.NO_MATCH;
}
}
|
itself
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/googleaistudio/GoogleAiStudioRequestManager.java
|
{
"start": 496,
"end": 1071
}
|
class ____ extends BaseRequestManager {
GoogleAiStudioRequestManager(ThreadPool threadPool, GoogleAiStudioModel model) {
super(threadPool, model.getInferenceEntityId(), RateLimitGrouping.of(model), model.rateLimitServiceSettings().rateLimitSettings());
}
record RateLimitGrouping(int modelIdHash) {
public static RateLimitGrouping of(GoogleAiStudioModel model) {
Objects.requireNonNull(model);
return new RateLimitGrouping(model.rateLimitServiceSettings().modelId().hashCode());
}
}
}
|
GoogleAiStudioRequestManager
|
java
|
elastic__elasticsearch
|
modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/SearchAsYouTypeFieldMapper.java
|
{
"start": 24997,
"end": 32609
}
|
class ____ extends StringFieldType {
final int shingleSize;
PrefixFieldType prefixFieldType;
ShingleFieldType(String name, int shingleSize, TextSearchInfo textSearchInfo) {
super(name, IndexType.terms(true, false), false, textSearchInfo, Collections.emptyMap());
this.shingleSize = shingleSize;
}
void setPrefixFieldType(PrefixFieldType prefixFieldType) {
this.prefixFieldType = prefixFieldType;
}
@Override
public boolean mayExistInIndex(SearchExecutionContext context) {
return false;
}
@Override
public ValueFetcher valueFetcher(SearchExecutionContext context, String format) {
// Because this internal field is modelled as a multi-field, SourceValueFetcher will look up its
// parent field in _source. So we don't need to use the parent field name here.
return SourceValueFetcher.toString(name(), context, format);
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public Query prefixQuery(
String value,
MultiTermQuery.RewriteMethod method,
boolean caseInsensitive,
SearchExecutionContext context
) {
if (prefixFieldType == null || prefixFieldType.termLengthWithinBounds(value.length()) == false) {
return super.prefixQuery(value, method, caseInsensitive, context);
} else {
final Query query = prefixFieldType.prefixQuery(value, method, caseInsensitive, context);
if (method == null
|| method == MultiTermQuery.CONSTANT_SCORE_REWRITE
|| method == MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE
|| method == MultiTermQuery.CONSTANT_SCORE_BLENDED_REWRITE) {
return new ConstantScoreQuery(query);
} else {
return query;
}
}
}
@Override
public Query phraseQuery(TokenStream stream, int slop, boolean enablePositionIncrements, SearchExecutionContext context)
throws IOException {
return TextFieldMapper.createPhraseQuery(stream, name(), slop, enablePositionIncrements);
}
@Override
public Query multiPhraseQuery(TokenStream stream, int slop, boolean enablePositionIncrements, SearchExecutionContext context)
throws IOException {
return TextFieldMapper.createPhraseQuery(stream, name(), slop, enablePositionIncrements);
}
@Override
public Query phrasePrefixQuery(TokenStream stream, int slop, int maxExpansions, SearchExecutionContext context) throws IOException {
final String prefixFieldName = slop > 0 ? null : prefixFieldType.name();
return TextFieldMapper.createPhrasePrefixQuery(
stream,
name(),
slop,
maxExpansions,
prefixFieldName,
prefixFieldType::termLengthWithinBounds
);
}
@Override
public SpanQuery spanPrefixQuery(String value, SpanMultiTermQueryWrapper.SpanRewriteMethod method, SearchExecutionContext context) {
if (prefixFieldType != null && prefixFieldType.termLengthWithinBounds(value.length())) {
return new FieldMaskingSpanQuery(new SpanTermQuery(new Term(prefixFieldType.name(), indexedValueForSearch(value))), name());
} else {
SpanMultiTermQueryWrapper<?> spanMulti = new SpanMultiTermQueryWrapper<>(
new PrefixQuery(new Term(name(), indexedValueForSearch(value)))
);
if (method != null) {
spanMulti.setRewriteMethod(method);
}
return spanMulti;
}
}
}
private final int maxShingleSize;
private final PrefixFieldMapper prefixField;
private final ShingleFieldMapper[] shingleFields;
private final Builder builder;
private final Map<String, NamedAnalyzer> indexAnalyzers;
public SearchAsYouTypeFieldMapper(
String simpleName,
SearchAsYouTypeFieldType mappedFieldType,
BuilderParams builderParams,
Map<String, NamedAnalyzer> indexAnalyzers,
PrefixFieldMapper prefixField,
ShingleFieldMapper[] shingleFields,
Builder builder
) {
super(simpleName, mappedFieldType, builderParams);
this.prefixField = prefixField;
this.shingleFields = shingleFields;
this.maxShingleSize = builder.maxShingleSize.getValue();
this.builder = builder;
this.indexAnalyzers = Map.copyOf(indexAnalyzers);
}
@Override
public Map<String, NamedAnalyzer> indexAnalyzers() {
return indexAnalyzers;
}
@Override
protected void parseCreateField(DocumentParserContext context) throws IOException {
final String value = context.parser().textOrNull();
if (value == null) {
return;
}
if (this.builder.index.get() == false && this.builder.store.get() == false) {
return;
}
context.doc().add(new Field(fieldType().name(), value, fieldType().fieldType));
if (this.builder.index.get()) {
for (ShingleFieldMapper subFieldMapper : shingleFields) {
context.doc().add(new Field(subFieldMapper.fieldType().name(), value, subFieldMapper.getLuceneFieldType()));
}
context.doc().add(new Field(prefixField.fieldType().name(), value, prefixField.getLuceneFieldType()));
}
if (fieldType().fieldType.omitNorms()) {
context.addToFieldNames(fieldType().name());
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
public FieldMapper.Builder getMergeBuilder() {
return new Builder(leafName(), builder.indexCreatedVersion, builder.analyzers.indexAnalyzers).init(this);
}
public static String getShingleFieldName(String parentField, int shingleSize) {
return parentField + "._" + shingleSize + "gram";
}
@Override
public SearchAsYouTypeFieldType fieldType() {
return (SearchAsYouTypeFieldType) super.fieldType();
}
public int maxShingleSize() {
return maxShingleSize;
}
public PrefixFieldMapper prefixField() {
return prefixField;
}
public ShingleFieldMapper[] shingleFields() {
return shingleFields;
}
@Override
public Iterator<Mapper> iterator() {
return subfieldsAndMultifieldsIterator();
}
private Iterator<Mapper> subfieldsAndMultifieldsIterator() {
List<Mapper> subIterators = new ArrayList<>();
subIterators.add(prefixField);
subIterators.addAll(Arrays.asList(shingleFields));
return Iterators.concat(multiFieldsIterator(), subIterators.iterator());
}
@Override
public Iterator<Mapper> sourcePathUsedBy() {
return subfieldsAndMultifieldsIterator();
}
/**
* An analyzer wrapper to add a shingle token filter, an edge ngram token filter or both to its wrapped analyzer. When adding an edge
* ngrams token filter, it also adds a {@link TrailingShingleTokenFilter} to add extra position increments at the end of the stream
* to induce the shingle token filter to create tokens at the end of the stream smaller than the shingle size
*/
static
|
ShingleFieldType
|
java
|
apache__camel
|
components/camel-as2/camel-as2-component/src/test/java/org/apache/camel/component/as2/AbstractAS2ITSupport.java
|
{
"start": 1280,
"end": 2826
}
|
class ____ extends CamelTestSupport {
private static final String TEST_OPTIONS_PROPERTIES = "/test-options.properties";
@Override
protected CamelContext createCamelContext() throws Exception {
final CamelContext context = super.createCamelContext();
// read AS2 component configuration from TEST_OPTIONS_PROPERTIES
final Properties properties = TestSupport.loadExternalProperties(getClass(), TEST_OPTIONS_PROPERTIES);
Map<String, Object> options = new HashMap<>();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
options.put(entry.getKey().toString(), entry.getValue());
}
final AS2Configuration configuration = new AS2Configuration();
PropertyBindingSupport.bindProperties(context, configuration, options);
// add AS2Component to Camel context
final AS2Component component = new AS2Component(context);
component.setConfiguration(configuration);
context.addComponent("as2", component);
return context;
}
@SuppressWarnings("unchecked")
protected <T> T requestBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers)
throws CamelExecutionException {
return (T) template().requestBodyAndHeaders(endpointUri, body, headers);
}
@SuppressWarnings("unchecked")
protected <T> T requestBody(String endpoint, Object body) throws CamelExecutionException {
return (T) template().requestBody(endpoint, body);
}
}
|
AbstractAS2ITSupport
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2363BasedirAwareFileActivatorTest.java
|
{
"start": 1040,
"end": 2663
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that the file-based profile activator resolves relative paths against the current project's base directory
* and also interpolates ${basedir} if explicitly given, just like usual for other parts of the POM.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-2363");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteDirectory("sub-a/target");
verifier.deleteDirectory("sub-b/target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyFilePresent("target/parent1.txt");
verifier.verifyFilePresent("target/parent2.txt");
verifier.verifyFileNotPresent("target/file1.txt");
verifier.verifyFileNotPresent("target/file2.txt");
verifier.verifyFileNotPresent("sub-a/target/parent1.txt");
verifier.verifyFileNotPresent("sub-a/target/parent2.txt");
verifier.verifyFilePresent("sub-a/target/file1.txt");
verifier.verifyFileNotPresent("sub-a/target/file2.txt");
verifier.verifyFileNotPresent("sub-b/target/parent1.txt");
verifier.verifyFileNotPresent("sub-b/target/parent2.txt");
verifier.verifyFileNotPresent("sub-b/target/file1.txt");
verifier.verifyFilePresent("sub-b/target/file2.txt");
}
}
|
MavenITmng2363BasedirAwareFileActivatorTest
|
java
|
quarkusio__quarkus
|
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/RemovedConfigPropertyTest.java
|
{
"start": 384,
"end": 775
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClass(RemovedConfigBean.class));
@Test
void skipConfigValidation() {
assertEquals(0, Arc.container().beanManager().getBeans(RemovedConfigBean.class).size());
}
@ApplicationScoped
public static
|
RemovedConfigPropertyTest
|
java
|
spring-projects__spring-framework
|
spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java
|
{
"start": 3106,
"end": 3310
}
|
class ____ extends LazyInitTargetSource {
@Override
protected void postProcessTargetObject(Object targetObject) {
((ITestBean) targetObject).setName("Rob Harrop");
}
}
}
|
CustomLazyInitTargetSource
|
java
|
apache__camel
|
components/camel-zeebe/src/test/java/org/apache/camel/component/zeebe/model/ProcessResponseTest.java
|
{
"start": 1077,
"end": 3220
}
|
class ____ {
private static final String MARSHAL_TEST_RESULT_1
= "{\"success\":true,\"process_id\":\"testProcess\",\"process_instance_key\":111,\"process_version\":2,\"process_key\":111}";
private static final String MARSHAL_TEST_RESULT_2
= "{\"success\":false,\"error_message\":\"Test Error\",\"error_code\":\"TestCode\",\"process_id\":\"testProcess\",\"process_instance_key\":111,\"process_version\":2,\"process_key\":111}";
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
public void marshalTest() {
ProcessResponse message = new ProcessResponse();
message.setProcessId("testProcess");
message.setProcessKey(111);
message.setProcessInstanceKey(111);
message.setProcessVersion(2);
message.setSuccess(true);
String messageString = assertDoesNotThrow(() -> objectMapper.writeValueAsString(message));
assertEquals(MARSHAL_TEST_RESULT_1, messageString);
message.setSuccess(false);
message.setErrorMessage("Test Error");
message.setErrorCode("TestCode");
messageString = assertDoesNotThrow(() -> objectMapper.writeValueAsString(message));
assertEquals(MARSHAL_TEST_RESULT_2, messageString);
}
@Test
public void unmarshalTest() {
ProcessResponse unmarshalledMessage1
= assertDoesNotThrow(() -> objectMapper.readValue(MARSHAL_TEST_RESULT_1, ProcessResponse.class));
ProcessResponse message = new ProcessResponse();
message.setProcessId("testProcess");
message.setProcessKey(111);
message.setProcessInstanceKey(111);
message.setProcessVersion(2);
message.setSuccess(true);
assertEquals(message, unmarshalledMessage1);
ProcessResponse unmarshalledMessage2
= assertDoesNotThrow(() -> objectMapper.readValue(MARSHAL_TEST_RESULT_2, ProcessResponse.class));
message.setSuccess(false);
message.setErrorMessage("Test Error");
message.setErrorCode("TestCode");
assertEquals(message, unmarshalledMessage2);
}
}
|
ProcessResponseTest
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-common/src/main/java/io/quarkus/cli/plugin/Binaries.java
|
{
"start": 246,
"end": 1470
}
|
class ____ {
public static Predicate<File> WITH_QUARKUS_PREFIX = f -> f.getName().startsWith("quarkus-");
private Binaries() {
//Utility class
}
public static Stream<File> streamCommands() {
return Arrays.stream(System.getenv().getOrDefault("PATH", "").split(File.pathSeparator))
.map(String::trim)
.filter(p -> p != null && !p.isEmpty())
.map(p -> new File(p))
.filter(File::exists)
.filter(File::isDirectory)
.flatMap(d -> Arrays.stream(d.listFiles()))
.filter(File::isFile)
.filter(File::canExecute);
}
public static Set<File> findCommands(Predicate<File> filter) {
return streamCommands()
.filter(filter)
.collect(Collectors.toSet());
}
public static Set<File> findCommands() {
return findCommands(f -> true);
}
public static Set<File> findQuarkusPrefixedCommands() {
return findCommands(WITH_QUARKUS_PREFIX);
}
public static Optional<File> pathOfComamnd(String name) {
return streamCommands().filter(f -> f.getName().equals(name)).findFirst();
}
}
|
Binaries
|
java
|
netty__netty
|
transport/src/main/java/io/netty/bootstrap/AbstractBootstrap.java
|
{
"start": 7528,
"end": 7614
}
|
class ____.
* <p>
* By default, the extensions will be loaded by the same
|
loader
|
java
|
google__guice
|
core/test/com/google/inject/MethodInterceptionTest.java
|
{
"start": 2332,
"end": 2434
}
|
class ____ {
private AtomicInteger count = new AtomicInteger();
private final
|
MethodInterceptionTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/assignment/AllocationStatus.java
|
{
"start": 853,
"end": 929
}
|
class ____ implements Writeable, ToXContentObject {
public
|
AllocationStatus
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/ast/ClassElement.java
|
{
"start": 31655,
"end": 31960
}
|
class ____
*/
@Internal
@NonNull
static ClassElement of(@NonNull String typeName, boolean isInterface, @Nullable AnnotationMetadata annotationMetadata, Map<String, ClassElement> typeArguments) {
return new SimpleClassElement(typeName, isInterface, annotationMetadata);
}
}
|
element
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/test/java/io/quarkus/qute/EngineTest.java
|
{
"start": 777,
"end": 4978
}
|
class ____ {
@Test
public void testMapResut() {
Engine engine = Engine.builder().addResultMapper((res, expr) -> "FOO").addResultMapper(new ResultMapper() {
@Override
public int getPriority() {
// Is executed before the FOO mapper
return 10;
}
@Override
public boolean appliesTo(Origin origin, Object result) {
return result instanceof Integer;
}
@Override
public String map(Object result, Expression expression) {
return "" + ((Integer) result) * 10;
}
}).build();
Template test = engine.parse("{foo}");
assertEquals("50",
engine.mapResult(5, test.getExpressions().iterator().next()));
assertEquals("FOO",
engine.mapResult("bar", test.getExpressions().iterator().next()));
}
@Test
public void testLocate() {
assertEquals(Optional.empty(), Engine.builder().addDefaults().build().locate("foo"));
Engine engine = Engine.builder().addDefaultSectionHelpers().addLocator(id -> Optional.of(new TemplateLocation() {
@Override
public Reader read() {
return new StringReader("{foo}");
}
@Override
public Optional<Variant> getVariant() {
return Optional.empty();
}
})).build();
Optional<TemplateLocation> location = engine.locate("foo");
assertTrue(location.isPresent());
try (Reader r = location.get().read()) {
char[] buffer = new char[4096];
StringBuilder b = new StringBuilder();
int num;
while ((num = r.read(buffer)) >= 0) {
b.append(buffer, 0, num);
}
assertEquals("{foo}", b.toString());
} catch (IOException e) {
fail(e);
}
}
@Test
public void testNewBuilder() {
Engine engine1 = Engine.builder()
.addNamespaceResolver(NamespaceResolver.builder("foo").resolve(ec -> "baz").build())
.addDefaults()
.strictRendering(false)
.useAsyncTimeout(false)
.timeout(20_000)
.addParserHook(new ParserHook() {
@Override
public void beforeParsing(ParserHelper parserHelper) {
parserHelper.addContentFilter(s -> s + "::{cool}");
}
})
.addTemplateInstanceInitializer(new Initializer() {
@Override
public void accept(TemplateInstance templateInstance) {
templateInstance.data("cool", true);
}
})
.build();
assertEquals("foo::baz::true", engine1.parse("{ping}::{foo:whatever}").data("ping", "foo").render());
assertFalse(engine1.getEvaluator().strictRendering());
assertFalse(engine1.useAsyncTimeout());
assertEquals(20_000, engine1.getTimeout());
Engine engine2 = engine1.newBuilder()
.useAsyncTimeout(true)
.addValueResolver(
// This value resolver has the highest priority
ValueResolver.builder().applyToName("ping").priority(Integer.MAX_VALUE).resolveWith("pong").build())
.build();
assertEquals("pong::baz::true", engine2.parse("{ping}::{foo:whatever}").data("ping", "foo").render());
assertEquals(20_000, engine2.getTimeout());
assertFalse(engine2.getEvaluator().strictRendering());
assertTrue(engine2.useAsyncTimeout());
assertEquals(engine1.getSectionHelperFactories().size(), engine2.getSectionHelperFactories().size());
}
@Test
public void testInvalidTemplateIdentifier() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> Engine.builder().build().putTemplate("foo o", null));
assertEquals("Invalid identifier found: [foo o]", e.getMessage());
}
private
|
EngineTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.