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
quarkusio__quarkus
extensions/panache/hibernate-reactive-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/reactive/rest/data/panache/deployment/security/repository/SecuredPanacheRepositoryResourceTest.java
{ "start": 1318, "end": 7939 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(Collection.class, CollectionsResource.class, CollectionsRepository.class, AbstractEntity.class, AbstractItem.class, Item.class, EmptyListItem.class, EmptyListItemsRepository.class, EmptyListItemsResource.class, PermissionCheckerBean.class) .addAsResource("application.properties") .addAsResource("import.sql")) .overrideConfigKey("quarkus.security.users.embedded.enabled", "true") .overrideConfigKey("quarkus.security.users.embedded.plain-text", "true") .overrideConfigKey("quarkus.security.users.embedded.users.foo", "foo") .overrideConfigKey("quarkus.security.users.embedded.roles.foo", "user") .overrideConfigKey("quarkus.security.users.embedded.users.bar", "bar") .overrideConfigKey("quarkus.security.users.embedded.roles.bar", "admin") .setForcedDependencies(List.of( Dependency.of("io.quarkus", "quarkus-security-deployment", Version.getVersion()), Dependency.of("io.quarkus", "quarkus-elytron-security-properties-file-deployment", Version.getVersion()))); @Test void defaultInterfaceMethodWithPermissionsAllowed() { // this endpoint requires permissions 'find-by-name-1' and 'find-by-name-2' // unauthenticated => 401 given().accept("application/hal+json") .when().get("/collections/name/full collection") .then().statusCode(401); // 'find-by-name-1' => 403 given().accept("application/hal+json") .auth().preemptive().basic("foo", "foo") .when().get("/collections/name/full collection") .then().statusCode(403); // 'find-by-name-1' && 'find-by-name-2' => 200 given().accept("application/hal+json") .auth().preemptive().basic("bar", "bar") .when().get("/collections/name/full collection") .then().statusCode(200) .and().body("id", is("full")) .and().body("name", is("full collection")) .and().body("_links.addByName.href", containsString("/name/full")); } @Test void defaultInterfaceMethodWithRolesAllowed() { // authentication is required => expect HTTP status 401 given().accept("application/json") .when().post("/collections/name/mycollection") .then().statusCode(401); // 'foo' has 'user' role, but 'admin' is required => expect HTTP status 403 given().accept("application/json") .auth().preemptive().basic("foo", "foo") .when().post("/collections/name/mycollection") .then().statusCode(403); // 'bar' has 'admin' role => expect HTTP status 200 given().accept("application/json") .auth().preemptive().basic("bar", "bar") .when().post("/collections/name/mycollection") .then().statusCode(200) .and().body("id", is("mycollection")) .and().body("name", is("mycollection")); } @Test void explicitlyDeclaredMethodWithPermissionsAllowed() { // this endpoint requires permissions 'get-1' and 'get-2' // unauthenticated => 401 given().accept("application/json") .when().get("/collections/full") .then().statusCode(401); // permission 'get-1' => 403 given().accept("application/json") .auth().preemptive().basic("foo", "foo") .when().get("/collections/full") .then().statusCode(403); // permission 'get-1' && 'get-2' => 200 given().accept("application/json") .auth().preemptive().basic("bar", "bar") .when().get("/collections/full") .then().statusCode(200) .and().body("id", is(equalTo("full"))) .and().body("name", is(equalTo("full collection"))) .and().body("items.id", contains(1, 2)) .and().body("items.name", contains("first", "second")); } @Test void testClassLevelPermissionsAllowed() { // authentication required => expect HTTP status 401 given().accept("application/hal+json") .and().queryParam("page", 1) .and().queryParam("size", 1) .when().get("/empty-list-items") .then().statusCode(401); // permission 'list-empty' is required => expect HTTP status 403 given().accept("application/hal+json") .auth().preemptive().basic("foo", "foo") .and().queryParam("page", 1) .and().queryParam("size", 1) .when().get("/empty-list-items") .then().statusCode(403); given().accept("application/hal+json") .auth().preemptive().basic("bar", "bar") .and().queryParam("page", 1) .and().queryParam("size", 1) .when().get("/empty-list-items") .then().statusCode(200); } @Test void testSecurityCheckBeforeSerialization() { given().accept("application/json") .contentType("application/json") .body("@$%*()^") .when().post("/collections") .then().statusCode(401); given().accept("application/json") .auth().preemptive().basic("foo", "foo") .contentType("application/json") .body("@$%*()^") .when().post("/collections") .then().statusCode(403); given().accept("application/json") .auth().preemptive().basic("bar", "bar") .contentType("application/json") .body("@$%*()^") .when().post("/collections") .then().statusCode(500); var collection = new Collection(); collection.name = "mine"; collection.id = "whatever"; given().accept("application/json") .auth().preemptive().basic("bar", "bar") .contentType("application/json") .body(collection) .when().post("/collections") .then().statusCode(201); } }
SecuredPanacheRepositoryResourceTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ConvertedEmbeddableCollectionTest.java
{ "start": 1986, "end": 2333 }
class ____ { @Id private Long id; @Convert( converter = EmbeddableConverter.class ) private Set<TestEmbeddable> embeddables = new HashSet<>(); public TestEntity() { } public TestEntity(Long id) { this.id = id; } public Set<TestEmbeddable> getEmbeddables() { return embeddables; } } @Converter public static
TestEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cdi/lifecycle/ExtendedBeanManagerNotAvailableDuringCustomUserTypeInitTest.java
{ "start": 1156, "end": 1941 }
class ____ { @Test public void tryIt() { // pass ExtendedBeanManager but never initialize it final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() .applySetting( AvailableSettings.JAKARTA_CDI_BEAN_MANAGER, new ExtendedBeanManagerImpl() ) .build(); // this will trigger initialization of dynamic parameterized user type bean //noinspection EmptyTryBlock try (var ignored = new MetadataSources(ssr) .addAnnotatedClass(TheEntity.class) .buildMetadata() .buildSessionFactory()) { } finally { StandardServiceRegistryBuilder.destroy(ssr); } } @SuppressWarnings("JpaDataSourceORMInspection") @Entity(name = "TheEntity") @Table(name = "TheEntity") public static
ExtendedBeanManagerNotAvailableDuringCustomUserTypeInitTest
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/test/java/org/springframework/boot/webmvc/autoconfigure/error/BasicErrorControllerDirectMockMvcTests.java
{ "start": 5404, "end": 5739 }
class ____ { // For manual testing static void main(String[] args) { new SpringApplicationBuilder(ParentConfiguration.class).child(ChildConfiguration.class).run(args); } } @Configuration(proxyBeanMethods = false) @EnableAspectJAutoProxy(proxyTargetClass = false) @MinimalWebConfiguration @Aspect static
ChildConfiguration
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/stats/Metrics.java
{ "start": 699, "end": 3722 }
enum ____ { FAILED, TOTAL; @Override public String toString() { return this.name().toLowerCase(Locale.ROOT); } } // map that holds total/failed counters for all queries, atm private final Map<QueryMetric, Map<OperationType, CounterMetric>> opsByTypeMetrics; // map that holds counters for each eql "feature" (join, pipe, sequence...) private final Map<FeatureMetric, CounterMetric> featuresMetrics; protected static String QPREFIX = "queries."; public Metrics() { Map<QueryMetric, Map<OperationType, CounterMetric>> qMap = new LinkedHashMap<>(); for (QueryMetric metric : QueryMetric.values()) { Map<OperationType, CounterMetric> metricsMap = Maps.newLinkedHashMapWithExpectedSize(OperationType.values().length); for (OperationType type : OperationType.values()) { metricsMap.put(type, new CounterMetric()); } qMap.put(metric, Collections.unmodifiableMap(metricsMap)); } opsByTypeMetrics = Collections.unmodifiableMap(qMap); Map<FeatureMetric, CounterMetric> fMap = Maps.newLinkedHashMapWithExpectedSize(FeatureMetric.values().length); for (FeatureMetric featureMetric : FeatureMetric.values()) { fMap.put(featureMetric, new CounterMetric()); } featuresMetrics = Collections.unmodifiableMap(fMap); } /** * Increments the "total" counter for a metric * This method should be called only once per query. */ public void total(QueryMetric metric) { inc(metric, OperationType.TOTAL); } /** * Increments the "failed" counter for a metric */ public void failed(QueryMetric metric) { inc(metric, OperationType.FAILED); } private void inc(QueryMetric metric, OperationType op) { this.opsByTypeMetrics.get(metric).get(op).inc(); } /** * Increments the counter for a "features" metric */ public void inc(FeatureMetric metric) { this.featuresMetrics.get(metric).inc(); } public Counters stats() { Counters counters = new Counters(); // queries metrics for (Entry<QueryMetric, Map<OperationType, CounterMetric>> entry : opsByTypeMetrics.entrySet()) { String metricName = entry.getKey().toString(); for (OperationType type : OperationType.values()) { long metricCounter = entry.getValue().get(type).count(); String operationTypeName = type.toString(); counters.inc(QPREFIX + metricName + "." + operationTypeName, metricCounter); counters.inc(QPREFIX + "_all." + operationTypeName, metricCounter); } } // features metrics for (Entry<FeatureMetric, CounterMetric> entry : featuresMetrics.entrySet()) { counters.inc(entry.getKey().prefixedName(), entry.getValue().count()); } return counters; } }
OperationType
java
apache__logging-log4j2
log4j-slf4j2-impl/src/main/java/org/apache/logging/slf4j/Log4jEventBuilder.java
{ "start": 1379, "end": 5124 }
class ____ implements LoggingEventBuilder, CallerBoundaryAware { private static final String FQCN = Log4jEventBuilder.class.getName(); private final Log4jMarkerFactory markerFactory; private final Logger logger; private final List<Object> arguments = new ArrayList<>(); private String message = null; private org.apache.logging.log4j.Marker marker = null; private Throwable throwable = null; private Map<String, String> keyValuePairs = null; private final Level level; private String fqcn = FQCN; public Log4jEventBuilder(final Log4jMarkerFactory markerFactory, final Logger logger, final Level level) { this.markerFactory = markerFactory; this.logger = logger; this.level = level; } @Override public LoggingEventBuilder setCause(final Throwable cause) { this.throwable = cause; return this; } @Override public LoggingEventBuilder addMarker(final Marker marker) { this.marker = markerFactory.getLog4jMarker(marker); return this; } @Override public LoggingEventBuilder addArgument(final Object p) { arguments.add(p); return this; } @Override public LoggingEventBuilder addArgument(final Supplier<?> objectSupplier) { arguments.add(objectSupplier.get()); return this; } @Override public LoggingEventBuilder addKeyValue(final String key, final Object value) { if (keyValuePairs == null) { keyValuePairs = new HashMap<>(); } keyValuePairs.put(key, String.valueOf(value)); return this; } @Override public LoggingEventBuilder addKeyValue(final String key, final Supplier<Object> valueSupplier) { if (keyValuePairs == null) { keyValuePairs = new HashMap<>(); } keyValuePairs.put(key, String.valueOf(valueSupplier.get())); return this; } @Override public LoggingEventBuilder setMessage(final String message) { this.message = message; return this; } @Override public LoggingEventBuilder setMessage(final Supplier<String> messageSupplier) { this.message = messageSupplier.get(); return this; } @Override public void log() { final LogBuilder logBuilder = logger.atLevel(level).withMarker(marker).withThrowable(throwable); if (logBuilder instanceof BridgeAware) { ((BridgeAware) logBuilder).setEntryPoint(fqcn); } if (keyValuePairs == null || keyValuePairs.isEmpty()) { logBuilder.log(message, arguments.toArray()); } else { try (final Instance c = CloseableThreadContext.putAll(keyValuePairs)) { logBuilder.log(message, arguments.toArray()); } } } @Override public void log(final String message) { setMessage(message); log(); } @Override public void log(final String message, final Object arg) { setMessage(message); addArgument(arg); log(); } @Override public void log(final String message, final Object arg0, final Object arg1) { setMessage(message); addArgument(arg0); addArgument(arg1); log(); } @Override public void log(final String message, final Object... args) { setMessage(message); for (final Object arg : args) { addArgument(arg); } log(); } @Override public void log(final Supplier<String> messageSupplier) { setMessage(messageSupplier); log(); } @Override public void setCallerBoundary(String fqcn) { this.fqcn = fqcn; } }
Log4jEventBuilder
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreator.java
{ "start": 1690, "end": 2076 }
interface ____ { /** * Create a callable statement in this connection. Allows implementations to use * CallableStatements. * @param con the Connection to use to create statement * @return a callable statement * @throws SQLException there is no need to catch SQLExceptions * that may be thrown in the implementation of this method. * The JdbcTemplate
CallableStatementCreator
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/InvokersChangedListener.java
{ "start": 862, "end": 921 }
interface ____ { void onChange(); }
InvokersChangedListener
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintThrowsConstraintViolationExceptionTest.java
{ "start": 1574, "end": 1942 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "CUSTOMER_ACCOUNT_NUMBER") public Long customerAccountNumber; @Basic(optional = false) @Column(name = "CUSTOMER_ID", unique = true) public String customerId; @Basic @Column(name = "BILLING_ADDRESS") public String billingAddress; public Customer() { } } }
Customer
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyEnableJmxTest.java
{ "start": 1416, "end": 6262 }
class ____ extends BaseJettyTest { @RegisterExtension protected AvailablePortFinder.Port port3 = AvailablePortFinder.find(); @RegisterExtension protected AvailablePortFinder.Port port4 = AvailablePortFinder.find(); private String serverUri0; private String serverUri1; private String serverUri2; private String serverUri3; private MBeanServerConnection mbsc; @Override public void doPostTearDown() throws Exception { releaseMBeanServers(); mbsc = null; testConfigurationBuilder.withDisableJMX(); } @Override public void doPreSetup() throws Exception { testConfigurationBuilder.withEnableJMX(); releaseMBeanServers(); } @Override protected void doPostSetup() { mbsc = getMBeanConnection(); } @Test public void testEnableJmxProperty() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); String expectedBody = "<html><body>foo</body></html>"; mock.expectedBodiesReceived(expectedBody, expectedBody, expectedBody, expectedBody); mock.expectedHeaderReceived("x", "foo"); template.requestBody(serverUri0 + "&x=foo", null, Object.class); template.requestBody(serverUri1 + "&x=foo", null, Object.class); template.requestBody(serverUri2 + "&x=foo", null, Object.class); template.requestBody(serverUri3 + "&x=foo", null, Object.class); MockEndpoint.assertIsSatisfied(context); Set<ObjectName> s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(2, s.size(), "Could not find 2 Jetty Server: " + s); } @Test public void testShutdown() throws Exception { Set<ObjectName> s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(2, s.size(), "Could not find 2 Jetty Server: " + s); context.stop(); s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(0, s.size(), "Could not find 0 Jetty Server: " + s); } @Test public void testEndpointDisconnect() throws Exception { Set<ObjectName> s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(2, s.size(), "Could not find 2 Jetty Server: " + s); context.getRouteController().stopRoute("route0"); s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(1, s.size(), "Could not find 1 Jetty Server: " + s); context.getRouteController().stopRoute("route2"); context.getRouteController().stopRoute("route3"); s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(1, s.size(), "Could not find 1 Jetty Server: " + s); context.getRouteController().stopRoute("route1"); s = mbsc.queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"), null); assertEquals(0, s.size(), "Could not find 0 Jetty Server: " + s); } @Override protected boolean useJmx() { return true; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { serverUri0 = "http://localhost:" + port1 + "/myservice?enableJmx=true"; serverUri1 = "http://localhost:" + port2 + "/myservice?enableJmx=true"; serverUri2 = "http://localhost:" + port3 + "/myservice?enableJmx=false"; serverUri3 = "http://localhost:" + port4 + "/myservice?enableJmx=false"; from("jetty:" + serverUri0).routeId("route0").setBody().simple("<html><body>${in.header.x}</body></html>") .to("mock:result"); from("jetty:" + serverUri1).routeId("route1").setBody().simple("<html><body>${in.header.x}</body></html>") .to("mock:result"); from("jetty:" + serverUri2).routeId("route2").setBody().simple("<html><body>${in.header.x}</body></html>") .to("mock:result"); from("jetty:" + serverUri3).routeId("route3").setBody().simple("<html><body>${in.header.x}</body></html>") .to("mock:result"); } }; } protected void releaseMBeanServers() { List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null); for (MBeanServer server : servers) { MBeanServerFactory.releaseMBeanServer(server); } } protected MBeanServerConnection getMBeanConnection() { if (mbsc == null) { mbsc = ManagementFactory.getPlatformMBeanServer(); } return mbsc; } }
JettyEnableJmxTest
java
apache__camel
components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisSelectListWithSplitTest.java
{ "start": 1052, "end": 2232 }
class ____ extends MyBatisTestSupport { @Test public void testSelectList() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); template.sendBody("direct:start", null); MockEndpoint.assertIsSatisfied(context); Account james = mock.getReceivedExchanges().get(0).getIn().getBody(Account.class); Account claus = mock.getReceivedExchanges().get(1).getIn().getBody(Account.class); assertEquals("James", james.getFirstName()); assertEquals("Claus", claus.getFirstName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 from("direct:start") .to("mybatis:selectAllAccounts?statementType=SelectList") // just use split body to split the List into individual objects .split(body()) .to("mock:result"); // END SNIPPET: e1 } }; } }
MyBatisSelectListWithSplitTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue944.java
{ "start": 536, "end": 664 }
class ____ { private int id; @Transient public int getId() { return id; } } }
Model
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_failWithActualExpectedAndMessage_Test.java
{ "start": 1243, "end": 4581 }
class ____ { private ConcreteAssert assertion; private Object actual = "Actual"; private Object expected = "Expected"; @BeforeEach void setup() { assertion = new ConcreteAssert("foo"); } @Test void should_fail_with_simple_message() { // WHEN AssertionFailedError afe = expectAssertionFailedError(() -> assertion.failWithActualExpectedAndMessage(actual, expected, "fail")); // THEN then(afe).hasMessage("fail"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_fail_with_message_having_args() { // WHEN AssertionFailedError afe = expectAssertionFailedError(() -> assertion.failWithActualExpectedAndMessage(actual, expected, "fail %d %s %%s", 5, "times")); // THEN then(afe).hasMessage("fail 5 times %s"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_keep_description_set_by_user() { // WHEN AssertionFailedError afe = expectAssertionFailedError(() -> assertion.as("user description") .failWithActualExpectedAndMessage(actual, expected, "fail %d %s", 5, "times")); // THEN then(afe).hasMessage("[user description] fail 5 times"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_keep_specific_error_message_and_description_set_by_user() { // WHEN AssertionFailedError afe = expectAssertionFailedError(() -> assertion.as("test context") .overridingErrorMessage("my %d errors %s", 5, "!") .failWithActualExpectedAndMessage(actual, expected, "%d %s", 5, "time")); // THEN then(afe).hasMessage("[test context] my 5 errors !"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } static AssertionFailedError expectAssertionFailedError(ThrowingCallable shouldRaiseAssertionError) { AssertionFailedError error = catchThrowableOfType(AssertionFailedError.class, shouldRaiseAssertionError); assertThat(error).as("The code under test should have raised an AssertionFailedError").isNotNull(); return error; } }
AbstractAssert_failWithActualExpectedAndMessage_Test
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java
{ "start": 1182, "end": 1354 }
class ____ implements ServiceListener { private List<ServiceConfig> exportedServices = new ArrayList<>(2); /** * Return the
AbstractRegistryCenterServiceListener
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2900/Issue2939.java
{ "start": 291, "end": 971 }
class ____ extends TestCase { public void test_for_issue() throws Exception { LinkedMultiValueMap multiValueMap = new LinkedMultiValueMap(); multiValueMap.add("k1","k11"); multiValueMap.add("k1","k12"); multiValueMap.add("k1","k13"); multiValueMap.add("k2","k21"); String json = JSON.toJSONString(multiValueMap); assertEquals("{\"k1\":[\"k11\",\"k12\",\"k13\"],\"k2\":[\"k21\"]}", json); Object obj = JSON.parseObject(json, LinkedMultiValueMap.class); assertTrue(obj != null); LinkedMultiValueMap map = (LinkedMultiValueMap) obj; assertSame(3, map.get("k1").size()); } }
Issue2939
java
redisson__redisson
redisson/src/main/java/org/redisson/executor/TasksRunnerService.java
{ "start": 1914, "end": 12537 }
class ____ implements RemoteExecutorService { private static final Map<HashValue, Codec> CODECS = new LRUCacheMap<>(500, 0, 0); private final Codec codec; private final String name; private final CommandAsyncExecutor commandExecutor; private final RedissonClient redisson; private String tasksCounterName; private String statusName; private String terminationTopicName; private String tasksName; private String schedulerQueueName; private String schedulerChannelName; private String tasksRetryIntervalName; private String tasksExpirationTimeName; private TasksInjector tasksInjector; public TasksRunnerService(CommandAsyncExecutor commandExecutor, RedissonClient redisson, Codec codec, String name) { this.commandExecutor = commandExecutor; this.name = name; this.redisson = redisson; this.codec = codec; } public void setTasksInjector(TasksInjector tasksInjector) { this.tasksInjector = tasksInjector; } public void setTasksExpirationTimeName(String tasksExpirationTimeName) { this.tasksExpirationTimeName = tasksExpirationTimeName; } public void setTasksRetryIntervalName(String tasksRetryInterval) { this.tasksRetryIntervalName = tasksRetryInterval; } public void setSchedulerQueueName(String schedulerQueueName) { this.schedulerQueueName = schedulerQueueName; } public void setSchedulerChannelName(String schedulerChannelName) { this.schedulerChannelName = schedulerChannelName; } public void setTasksName(String tasksName) { this.tasksName = tasksName; } public void setTasksCounterName(String tasksCounterName) { this.tasksCounterName = tasksCounterName; } public void setStatusName(String statusName) { this.statusName = statusName; } public void setTerminationTopicName(String terminationTopicName) { this.terminationTopicName = terminationTopicName; } @Override public void scheduleAtFixedRate(ScheduledAtFixedRateParameters params) { long start = System.nanoTime(); executeRunnable(params, false); if (!redisson.getMap(tasksName, StringCodec.INSTANCE).containsKey(params.getRequestId())) { return; } long spent = params.getSpentTime() + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long newStartTime = System.currentTimeMillis() + Math.max(params.getPeriod() - spent, 0); params.setStartTime(newStartTime); spent = Math.max(spent - params.getPeriod(), 0); params.setSpentTime(spent); asyncScheduledServiceAtFixed(params.getExecutorId(), params.getRequestId()).scheduleAtFixedRate(params); } @Override public void schedule(ScheduledCronExpressionParameters params) { CronExpression expression = new CronExpression(params.getCronExpression()); expression.setTimeZone(TimeZone.getTimeZone(params.getTimezone())); Date nextStartDate = expression.getNextValidTimeAfter(new Date()); executeRunnable(params, nextStartDate == null); if (nextStartDate == null || !redisson.getMap(tasksName, StringCodec.INSTANCE).containsKey(params.getRequestId())) { return; } params.setStartTime(nextStartDate.getTime()); asyncScheduledServiceAtFixed(params.getExecutorId(), params.getRequestId()).schedule(params); } /** * Creates RemoteExecutorServiceAsync with special executor which overrides requestId generation * and uses current requestId. Because recurring tasks should use the same requestId. * * @return */ private RemoteExecutorServiceAsync asyncScheduledServiceAtFixed(String executorId, String requestId) { ScheduledTasksService scheduledRemoteService = new ScheduledTasksService(codec, name, commandExecutor, executorId); scheduledRemoteService.setTerminationTopicName(terminationTopicName); scheduledRemoteService.setTasksCounterName(tasksCounterName); scheduledRemoteService.setStatusName(statusName); scheduledRemoteService.setSchedulerQueueName(schedulerQueueName); scheduledRemoteService.setSchedulerChannelName(schedulerChannelName); scheduledRemoteService.setTasksName(tasksName); scheduledRemoteService.setRequestId(requestId); scheduledRemoteService.setTasksExpirationTimeName(tasksExpirationTimeName); scheduledRemoteService.setTasksRetryIntervalName(tasksRetryIntervalName); RemoteExecutorServiceAsync asyncScheduledServiceAtFixed = scheduledRemoteService.get(RemoteExecutorServiceAsync.class, RemoteInvocationOptions.defaults().noAck().noResult()); return asyncScheduledServiceAtFixed; } @Override public void scheduleWithFixedDelay(ScheduledWithFixedDelayParameters params) { executeRunnable(params, false); long newStartTime = System.currentTimeMillis() + params.getDelay(); params.setStartTime(newStartTime); asyncScheduledServiceAtFixed(params.getExecutorId(), params.getRequestId()).scheduleWithFixedDelay(params); } @Override public Object scheduleCallable(ScheduledParameters params) { return executeCallable(params); } @Override public void scheduleRunnable(ScheduledParameters params) { executeRunnable(params); } @Override public Object executeCallable(TaskParameters params) { Object res; try { RFuture<Long> future = renewRetryTime(params.getRequestId()); future.toCompletableFuture().get(); Callable<?> callable = decode(params); res = callable.call(); } catch (RedissonShutdownException e) { throw e; } catch (RedisException e) { finish(params.getRequestId(), true); throw e; } catch (ExecutionException e) { finish(params.getRequestId(), true); if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new IllegalArgumentException(e.getCause()); } } catch (Exception e) { finish(params.getRequestId(), true); throw new IllegalArgumentException(e); } finish(params.getRequestId(), true); return res; } protected void scheduleRetryTimeRenewal(String requestId, Long retryInterval) { if (retryInterval == null) { return; } commandExecutor.getServiceManager().newTimeout(timeout -> renewRetryTime(requestId), Math.max(1000, retryInterval / 2), TimeUnit.MILLISECONDS); } protected RFuture<Long> renewRetryTime(String requestId) { RFuture<Long> future = commandExecutor.evalWriteAsync(name, LongCodec.INSTANCE, RedisCommands.EVAL_LONG, // check if executor service not in shutdown state "local name = ARGV[2];" + "local scheduledName = ARGV[2];" + "if string.sub(scheduledName, 1, 3) ~= 'ff:' then " + "scheduledName = 'ff:' .. scheduledName; " + "else " + "name = string.sub(name, 4, string.len(name)); " + "end;" + "local retryInterval = redis.call('get', KEYS[4]);" + "if redis.call('exists', KEYS[1]) == 0 and retryInterval ~= false and redis.call('hexists', KEYS[5], name) == 1 then " + "local startTime = tonumber(ARGV[1]) + tonumber(retryInterval);" + "redis.call('zadd', KEYS[2], startTime, scheduledName);" + "local v = redis.call('zrange', KEYS[2], 0, 0); " // if new task added to queue head then publish its startTime // to all scheduler workers + "if v[1] == scheduledName then " + "redis.call('publish', KEYS[3], startTime); " + "end;" + "return retryInterval; " + "end;" + "return nil;", Arrays.asList(statusName, schedulerQueueName, schedulerChannelName, tasksRetryIntervalName, tasksName), System.currentTimeMillis(), requestId); future.whenComplete((res, e) -> { if (e != null) { scheduleRetryTimeRenewal(requestId, 10000L); return; } if (res != null) { scheduleRetryTimeRenewal(requestId, res); } }); return future; } private HashValue hash(ClassLoader classLoader, String className) throws IOException { String classAsPath = className.replace('.', '/') + ".class"; InputStream classStream = classLoader.getResourceAsStream(classAsPath); if (classStream == null) { return HashValue.EMPTY; } ByteBuf out = ByteBufAllocator.DEFAULT.buffer(); out.writeBytes(classStream, classStream.available()); HashValue hash = new HashValue(Hash.hash128(out)); out.release(); return hash; } @SuppressWarnings("unchecked") private <T> T decode(TaskParameters params) { ByteBuf classBodyBuf = Unpooled.wrappedBuffer(params.getClassBody()); ByteBuf stateBuf = Unpooled.wrappedBuffer(params.getState()); try { HashValue hash = new HashValue(Hash.hash128(classBodyBuf)); Codec classLoaderCodec = CODECS.get(hash); if (classLoaderCodec == null) { HashValue v = hash(codec.getClassLoader(), params.getClassName()); if (v.equals(hash)) { classLoaderCodec = codec; } else { RedissonClassLoader cl = new RedissonClassLoader(codec.getClassLoader()); cl.loadClass(params.getClassName(), params.getClassBody()); classLoaderCodec = this.codec.getClass().getConstructor(ClassLoader.class).newInstance(cl); } CODECS.put(hash, classLoaderCodec); } T task; if (params.getLambdaBody() != null) { ByteArrayInputStream is = new ByteArrayInputStream(params.getLambdaBody()); //set thread context
TasksRunnerService
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java
{ "start": 16893, "end": 17060 }
class ____ implements Parser<Integer> { @Override public Integer parse(String text, Locale locale) throws ParseException { return 1; } } static
ExampleParser
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableCombineLatest.java
{ "start": 13259, "end": 14697 }
class ____<T> extends AtomicReference<Subscription> implements FlowableSubscriber<T> { private static final long serialVersionUID = -8730235182291002949L; final CombineLatestCoordinator<T, ?> parent; final int index; final int prefetch; final int limit; int produced; CombineLatestInnerSubscriber(CombineLatestCoordinator<T, ?> parent, int index, int prefetch) { this.parent = parent; this.index = index; this.prefetch = prefetch; this.limit = prefetch - (prefetch >> 2); } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, prefetch); } @Override public void onNext(T t) { parent.innerValue(index, t); } @Override public void onError(Throwable t) { parent.innerError(index, t); } @Override public void onComplete() { parent.innerComplete(index); } public void cancel() { SubscriptionHelper.cancel(this); } public void requestOne() { int p = produced + 1; if (p == limit) { produced = 0; get().request(p); } else { produced = p; } } } final
CombineLatestInnerSubscriber
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/io/VFS.java
{ "start": 1586, "end": 1969 }
class ____ { static final VFS INSTANCE = createVFS(); @SuppressWarnings("unchecked") static VFS createVFS() { // Try the user implementations first, then the built-ins List<Class<? extends VFS>> impls = new ArrayList<>(USER_IMPLEMENTATIONS); impls.addAll(Arrays.asList((Class<? extends VFS>[]) IMPLEMENTATIONS)); // Try each implementation
VFSHolder
java
junit-team__junit5
documentation/src/test/java/example/ExternalMethodSourceDemo.java
{ "start": 513, "end": 711 }
class ____ { @ParameterizedTest @MethodSource("example.StringsProviders#tinyStrings") void testWithExternalMethodSource(String tinyString) { // test with tiny string } }
ExternalMethodSourceDemo
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/model/MySubclassEntity.java
{ "start": 199, "end": 448 }
class ____ extends MyEntity { private String someSubProperty; public String getSomeSubProperty() { return someSubProperty; } public void setSomeSubProperty(String someSubProperty) { this.someSubProperty = someSubProperty; } }
MySubclassEntity
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractDateAssert.java
{ "start": 3105, "end": 129661 }
class ____<SELF extends AbstractDateAssert<SELF>> extends AbstractAssertWithComparator<SELF, Date> { private static final String DATE_FORMAT_PATTERN_SHOULD_NOT_BE_NULL = "Given date format pattern should not be null"; private static final String DATE_FORMAT_SHOULD_NOT_BE_NULL = "Given date format should not be null"; private static boolean lenientParsing = Configuration.LENIENT_DATE_PARSING; /** * the default DateFormat used to parse any String date representation. */ private static final ThreadLocal<List<DateFormat>> DEFAULT_DATE_FORMATS = ThreadLocal.withInitial(() -> list(newIsoDateTimeWithMsAndIsoTimeZoneFormat(lenientParsing), newIsoDateTimeWithMsFormat(lenientParsing), newTimestampDateFormat(lenientParsing), newIsoDateTimeWithIsoTimeZoneFormat(lenientParsing), newIsoDateTimeFormat(lenientParsing), newIsoDateFormat(lenientParsing))); // TODO reduce the visibility of the fields annotated with @VisibleForTesting static List<DateFormat> defaultDateFormats() { if (defaultDateFormatMustBeRecreated()) { DEFAULT_DATE_FORMATS.remove(); } return DEFAULT_DATE_FORMATS.get(); } private static boolean defaultDateFormatMustBeRecreated() { // check default timezone or lenient flag changes, only check one date format since all are configured the same way DateFormat dateFormat = DEFAULT_DATE_FORMATS.get().get(0); return !dateFormat.getTimeZone().getID().equals(TimeZone.getDefault().getID()) || dateFormat.isLenient() != lenientParsing; } /** * Used in String based Date assertions - like {@link #isAfter(String)} - to convert input date represented as string * to Date.<br> * It keeps the insertion order, so the first format added will be the first format used. */ // TODO reduce the visibility of the fields annotated with @VisibleForTesting static ThreadLocal<LinkedHashSet<DateFormat>> userDateFormats = ThreadLocal.withInitial(LinkedHashSet::new); // TODO reduce the visibility of the fields annotated with @VisibleForTesting Dates dates = Dates.instance(); protected AbstractDateAssert(Date actual, Class<?> selfType) { super(actual, selfType); } /** * Same assertion as {@link AbstractAssert#isEqualTo(Object) isEqualTo(Date date)} but given date is represented as * a {@code String} either with one of the supported default date formats or a user custom date format set with method * {@link #withDateFormat(DateFormat)}. * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isEqualTo("2002-12-18"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isEqualTo("2002-12-19");</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual and given Date represented as String are not equal. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isEqualTo(String dateAsString) { return isEqualTo(parse(dateAsString)); } /** * Calls {@link AbstractAssert#isEqualTo(Object) isEqualTo(Date date)} after converting the given {@code Instant} to a * {@code Date}. * <p> * Example: * <pre><code class='java'> // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isEqualTo(Instant.parse("2002-12-18T00:00:00.00Z"));</code></pre> * * @param instant the given {@code Instant} to compare to actual. * @return this assertion object. * @throws NullPointerException if given {@code Instant} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@link Instant} are not equal (after converting instant to a Date). */ public SELF isEqualTo(Instant instant) { return isEqualTo(dateFrom(instant)); } /** * Same assertion as {@link AbstractAssert#isNotEqualTo(Object) isNotEqualTo(Date date)} but given date is * represented as String either with one of the supported default date formats or a user custom date format (set with * method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isNotEqualTo("2002-12-19"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isNotEqualTo("2002-12-18")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual and given Date represented as String are equal. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isNotEqualTo(String dateAsString) { return isNotEqualTo(parse(dateAsString)); } /** * Same assertion as {@link AbstractAssert#isNotEqualTo(Object) isNotEqualTo(Date date)} but given date is * represented as an {@code java.time.Instant}. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isNotEqualTo(Instant.now());</code></pre> * * @param instant the given {@code Instant}. * @return this assertion object. * @throws AssertionError if actual {@code Date} and given {@code Instant} are equal. * @since 3.19.0 */ public SELF isNotEqualTo(Instant instant) { return isNotEqualTo(dateFrom(instant)); } /** * Same assertion as {@link Assert#isIn(Object...)}but given dates are represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isIn("2002-12-17", "2002-12-18", "2002-12-19"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isIn("2002-12-17", "2002-12-19", "2002-12-20")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param datesAsString the given Dates represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual is not in given Dates represented as String. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isIn(String... datesAsString) { Date[] dates = toDateArray(datesAsString, this::parse); return isIn((Object[]) dates); } /** * Same assertion as {@link Assert#isIn(Object...) }but given dates are represented as an {@code java.time.Instant}. * <p> * Example: * <pre><code class='java'> // assertion will fail * // theTwoTowers release date : 2002-12-18 * Instant now = Instant.now() * assertThat(theTwoTowers.getReleaseDate()).isIn(now, now.plusSeconds(5), now.minusSeconds(5));</code></pre> * * @param instants the given dates represented as {@code Instant}. * @return this assertion object. * @throws AssertionError if actual is not in given dates represented as {@code Instant}. */ public SELF isIn(Instant... instants) { Date[] dates = toDateArray(instants, Date::from); return isIn((Object[]) dates); } /** * Same assertion as {@link Assert#isIn(Iterable)} but given dates are represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isInWithStringDateCollection(asList("2002-12-17", "2002-12-18", "2002-12-19")); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isInWithStringDateCollection(asList("2002-12-17", "2002-12-19", "2002-12-20"))</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * <p> * Method signature could not be <code>isIn(Collection&lt;String&gt;)</code> because it would be same signature as * <code>isIn(Collection&lt;Date&gt;)</code> since java collection type are erased at runtime. * * @param datesAsString the given Dates represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual is not in given Dates represented as String. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isInWithStringDateCollection(Collection<String> datesAsString) { return isIn(datesAsString.stream().map(this::parse).collect(toList())); } /** * Same assertion as {@link Assert#isNotIn(Object...)} but given dates are represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isNotIn("2002-12-17", "2002-12-19"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isNotIn("2002-12-17", "2002-12-18")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param datesAsString the given Dates represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual is in given Dates represented as String. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isNotIn(String... datesAsString) { Date[] dates = toDateArray(datesAsString, this::parse); return isNotIn((Object[]) dates); } /** * Same assertion as {@link Assert#isNotIn(Object...)} but given dates are represented as {@code java.time.Instant}. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * Instant now = Instant.now() * assertThat(theTwoTowers.getReleaseDate()).isIn(now, now.plusSeconds(5), now.minusSeconds(5));</code></pre> * * @param instants the given dates represented as {@code Instant}. * @return this assertion object. * @throws AssertionError if actual is not in given dates represented as {@code Instant}. * @since 3.19.0 */ public SELF isNotIn(Instant... instants) { Date[] dates = toDateArray(instants, Date::from); return isNotIn((Object[]) dates); } /** * Same assertion as {@link Assert#isNotIn(Iterable)} but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isNotInWithStringDateCollection(Arrays.asList("2002-12-17", "2002-12-19")); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isNotInWithStringDateCollection(Arrays.asList("2002-12-17", "2002-12-18"))</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * Method signature could not be <code>isNotIn(Collection&lt;String&gt;)</code> because it would be same signature as * <code>isNotIn(Collection&lt;Date&gt;)</code> since java collection type are erased at runtime. * * @param datesAsString the given Dates represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if actual is in given Dates represented as String. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isNotInWithStringDateCollection(Collection<String> datesAsString) { return isNotIn(datesAsString.stream().map(this::parse).collect(toList())); } /** * Verifies that the actual {@code Date} is <b>strictly</b> before the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBefore(theReturnOfTheKing.getReleaseDate()); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBefore(theFellowshipOfTheRing.getReleaseDate());</code></pre> * * @param other the given Date. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly before the given one. */ public SELF isBefore(Date other) { dates.assertIsBefore(info, actual, other); return myself; } /** * Verifies that the actual {@code Date} is <b>strictly</b> before the given {@link Instant}. * <p> * Example: * <pre><code class='java'> // assertion succeeds * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBefore(Instant.parse("2002-12-19T00:00:00.00Z")); * * // assertions fail * assertThat(theTwoTowers.getReleaseDate()).isBefore(Instant.parse("2002-12-17T00:00:00.00Z")); * assertThat(theTwoTowers.getReleaseDate()).isBefore(Instant.parse("2002-12-18T00:00:00.00Z"));</code></pre> * * @param other the given {@code Instant}. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly before the given {@code Instant}. * @since 3.19.0 */ public SELF isBefore(Instant other) { dates.assertIsBefore(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isBefore(Date)} but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBefore("2002-12-19"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBefore("2002-12-17"); * assertThat(theTwoTowers.getReleaseDate()).isBefore("2002-12-18")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if given date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly before the given Date represented as * String. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isBefore(String dateAsString) { return isBefore(parse(dateAsString)); } /** * Verifies that the actual {@code Date} is before or equal to the given one. * <p> * Example: * <pre><code class='java'> SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * * // assertions will pass * assertThat(dateFormat.parse(&quot;1990-12-01&quot;)).isBeforeOrEqualTo(dateFormat.parse(&quot;2000-12-01&quot;)); * assertThat(dateFormat.parse(&quot;2000-12-01&quot;)).isBeforeOrEqualTo(dateFormat.parse(&quot;2000-12-01&quot;)); * * // assertion will fail * assertThat(dateFormat.parse(&quot;2000-12-01&quot;)).isBeforeOrEqualTo(dateFormat.parse(&quot;1990-12-01&quot;));</code></pre> * * @param other the given Date. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not before or equals to the given one. */ public SELF isBeforeOrEqualTo(Date other) { dates.assertIsBeforeOrEqualTo(info, actual, other); return myself; } /** * Verifies that the actual {@code Date} is before or equal to the given {@link Instant}. * <p> * Example: * <pre><code class='java'> // assertions succeed * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo(Instant.parse("2002-12-19T00:00:00.00Z")); * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo(Instant.parse("2002-12-18T00:00:00.00Z")); * * // assertion fails * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo(Instant.parse("2002-12-17T00:00:00.00Z"));</code></pre> * * @param other the given {@code Instant}. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is not before or equal to the given {@code Instant}. * @since 3.19.0 */ public SELF isBeforeOrEqualTo(Instant other) { dates.assertIsBeforeOrEqualTo(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isBeforeOrEqualTo(Date)} but given date is represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo("2002-12-19"); * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo("2002-12-18"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBeforeOrEqualTo("2002-12-17")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if given date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not before or equals to the given Date represented as * String. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isBeforeOrEqualTo(String dateAsString) { return isBeforeOrEqualTo(parse(dateAsString)); } /** * Verifies that the actual {@code Date} is <b>strictly</b> after the given one. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isAfter(theFellowshipOfTheRing.getReleaseDate()); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isAfter(theReturnOfTheKing.getReleaseDate());</code></pre> * * @param other the given Date. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly after the given one. */ public SELF isAfter(Date other) { dates.assertIsAfter(info, actual, other); return myself; } /** * Verifies that the actual {@code Date} is <b>strictly</b> after the given {@link Instant}. * <p> * Example: * <pre><code class='java'> // assertion succeeds * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isAfter(Instant.parse("2002-12-17T00:00:00.00Z")); * * // assertions fail * assertThat(theTwoTowers.getReleaseDate()).isAfter(Instant.parse("2002-12-18T00:00:00.00Z")); * assertThat(theTwoTowers.getReleaseDate()).isAfter(Instant.parse("2002-12-19T00:00:00.00Z"));</code></pre> * * @param other the given {@code Instant}. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly after the given {@code Instant}. * @since 3.19.0 */ public SELF isAfter(Instant other) { dates.assertIsAfter(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isAfter(Date)} but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isAfter("2002-12-17"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isAfter("2002-12-18"); * assertThat(theTwoTowers.getReleaseDate()).isAfter("2002-12-19")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if given date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not strictly after the given Date represented as * String. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isAfter(String dateAsString) { return isAfter(parse(dateAsString)); } /** * Verifies that the actual {@code Date} is after or equal to the given one. * <p> * Example: * <pre><code class='java'> SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * * // assertions will pass * assertThat(dateFormat.parse(&quot;2000-12-01&quot;)).isAfterOrEqualTo(dateFormat.parse(&quot;1990-12-01&quot;)); * assertThat(dateFormat.parse(&quot;2000-12-01&quot;)).isAfterOrEqualTo(dateFormat.parse(&quot;2000-12-01&quot;)); * * // assertion will fail * assertThat(dateFormat.parse(&quot;1990-12-01&quot;)).isAfterOrEqualTo(dateFormat.parse(&quot;2000-12-01&quot;));</code></pre> * * @param other the given Date. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not after or equals to the given one. */ public SELF isAfterOrEqualTo(Date other) { dates.assertIsAfterOrEqualTo(info, actual, other); return myself; } /** * Verifies that the actual {@code Date} is after or equal to the given {@link Instant}. * <p> * Example: * <pre><code class='java'> // assertions succeed * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).assertIsAfterOrEqualTo(Instant.parse("2002-12-17T00:00:00.00Z")) * .assertIsAfterOrEqualTo(Instant.parse("2002-12-18T00:00:00.00Z")); * // assertion fails * assertThat(theTwoTowers.getReleaseDate()).assertIsAfterOrEqualTo(Instant.parse("2002-12-19T00:00:00.00Z"));</code></pre> * * @param other the given {@code Instant}. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if other {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is not after or equal to the given {@code Instant}. * @since 3.19.0 */ public SELF isAfterOrEqualTo(Instant other) { dates.assertIsAfterOrEqualTo(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isAfterOrEqualTo(Date)} but given date is represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isAfterOrEqualTo("2002-12-17"); * assertThat(theTwoTowers.getReleaseDate()).isAfterOrEqualTo("2002-12-18"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isAfterOrEqualTo("2002-12-19")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if given date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not after or equals to the given Date represented as * String. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isAfterOrEqualTo(String dateAsString) { return isAfterOrEqualTo(parse(dateAsString)); } /** * Verifies that the actual {@code Date} is in [start, end[ period (start included, end excluded). * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBetween(theFellowshipOfTheRing.getReleaseDate(), theReturnOfTheKing.getReleaseDate()); * * // assertion will fail * assertThat(theFellowshipOfTheRing.getReleaseDate()).isBetween(theTwoTowers.getReleaseDate(), theReturnOfTheKing.getReleaseDate());</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start {@code Date} is {@code null}. * @throws NullPointerException if end {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in [start, end[ period. */ public SELF isBetween(Date start, Date end) { return isBetween(start, end, true, false); } /** * Same assertion as {@link #isBetween(Date, Date)} but given date is represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBetween("2002-12-17", "2002-12-19"); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBetween("2002-12-15", "2002-12-17")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start Date as String is {@code null}. * @throws NullPointerException if end Date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not in [start, end[ period. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isBetween(String start, String end) { return isBetween(parse(start), parse(end)); } /** * Same assertion as {@link #isBetween(Date, Date)} but given period is represented with {@link java.time.Instant}. * <p> * Example: * <pre><code class='java'> assertThat(new Date()).isBetween(Instant.now().minusSeconds(5), Instant.now().plusSeconds(5));</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start Instant as String is {@code null}. * @throws NullPointerException if end Instant as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not in [start, end[ period. * @since 3.19.0 */ public SELF isBetween(Instant start, Instant end) { return isBetween(dateFrom(start), dateFrom(end)); } /** * Verifies that the actual {@code Date} is in the given period defined by start and end dates.<br> * To include start * in the period set inclusiveStart parameter to <code>true</code>.<br> * To include end in the period set inclusiveEnd * parameter to <code>true</code>.<br> * <p> * Example: * <pre><code class='java'> SimpleDateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * // assertions will pass * assertThat(format.parse(&quot;2000-01-01&quot;)).isBetween(format.parse(&quot;2000-01-01&quot;), format.parse(&quot;2100-12-01&quot;), true, true); * assertThat(format.parse(&quot;2000-01-01&quot;)).isBetween(format.parse(&quot;1900-01-01&quot;), format.parse(&quot;2000-01-01&quot;), true, true); * assertThat(format.parse(&quot;2000-01-01&quot;)).isBetween(format.parse(&quot;1900-01-01&quot;), format.parse(&quot;2100-01-01&quot;), false, false); * * // assertions will fail * assertThat(format.parse(&quot;2000-01-01&quot;)).isBetween(format.parse(&quot;2000-01-01&quot;), format.parse(&quot;2100-12-01&quot;), false, true); * assertThat(format.parse(&quot;2000-01-01&quot;)).isBetween(format.parse(&quot;1900-01-01&quot;), format.parse(&quot;2000-01-01&quot;), true, false);</code></pre> * * @param start the period start, expected not to be null. * @param end the period end, expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start {@code Date} is {@code null}. * @throws NullPointerException if end {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. */ public SELF isBetween(Date start, Date end, boolean inclusiveStart, boolean inclusiveEnd) { dates.assertIsBetween(info, actual, start, end, inclusiveStart, inclusiveEnd); return myself; } /** * Same assertion as {@link #isBetween(Date, Date, boolean, boolean)} but given date is represented as String either * with one of the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBetween("2002-12-17", "2002-12-18", false, true); * assertThat(theTwoTowers.getReleaseDate()).isBetween("2002-12-18", "2002-12-19", true, false); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBetween("2002-12-17", "2002-12-18", false, false)</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param start the period start, expected not to be null. * @param end the period end, expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start Date as String is {@code null}. * @throws NullPointerException if end Date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isBetween(String start, String end, boolean inclusiveStart, boolean inclusiveEnd) { dates.assertIsBetween(info, actual, parse(start), parse(end), inclusiveStart, inclusiveEnd); return myself; } /** * Same assertion as {@link #isBetween(Date, Date, boolean, boolean)} but given period is represented with {@link java.time.Instant}. * <p> * Example: * <pre><code class='java'> assertThat(new Date()).isBetween(Instant.now().minusSeconds(5), Instant.now().plusSeconds(5), true, true);</code></pre> * * @param start the period start, expected not to be null. * @param end the period end, expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start Date as Instant is {@code null}. * @throws NullPointerException if end Date as Instant is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. * @since 3.19.0 */ public SELF isBetween(Instant start, Instant end, boolean inclusiveStart, boolean inclusiveEnd) { dates.assertIsBetween(info, actual, dateFrom(start), dateFrom(end), inclusiveStart, inclusiveEnd); return myself; } /** * Verifies that the actual {@code Date} is not in the given period defined by start and end dates.<br> * To include start in the period set inclusiveStart parameter to <code>true</code>.<br> * To include end in the period set inclusiveEnd parameter to <code>true</code>.<br> * <p> * Example: * <pre><code class='java'> SimpleDateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * // assertions will pass * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("2000-01-01"), format.parse("2100-12-01"), false, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01"), format.parse("2000-01-01"), true, false); * * // assertions will fail * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("2000-01-01"), format.parse("2100-12-01"), true, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01"), format.parse("2000-01-01"), true, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01"), format.parse("2100-01-01"), false, false);</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start {@code Date} is {@code null}. * @throws NullPointerException if end {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. */ public SELF isNotBetween(Date start, Date end, boolean inclusiveStart, boolean inclusiveEnd) { dates.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd); return myself; } /** * Verifies that the actual {@code Date} is not in the given period defined by start and end dates.<br> * To include start in the period set inclusiveStart parameter to <code>true</code>.<br> * To include end in the period set inclusiveEnd parameter to <code>true</code>.<br> * <p> * Example: * <pre><code class='java'> SimpleDateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * // assertions will pass * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("2000-01-01T00:00:00Z"), format.parse("2100-12-01T00:00:00Z"), false, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01T00:00:00Z"), format.parse("2000-01-01T00:00:00Z"), true, false); * * // assertions will fail * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("2000-01-01T00:00:00Z"), format.parse("2100-12-01T00:00:00Z"), true, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01T00:00:00Z"), format.parse("2000-01-01T00:00:00Z"), true, true); * assertThat(format.parse("2000-01-01")).isNotBetween(format.parse("1900-01-01T00:00:00Z"), format.parse("2100-01-01T00:00:00Z"), false, false);</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start {@code Instant} is {@code null}. * @throws NullPointerException if end {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. * @since 3.19.0 */ public SELF isNotBetween(Instant start, Instant end, boolean inclusiveStart, boolean inclusiveEnd) { dates.assertIsNotBetween(info, actual, dateFrom(start), dateFrom(end), inclusiveStart, inclusiveEnd); return myself; } /** * Same assertion as {@link #isNotBetween(Date, Date, boolean, boolean)} but given date is represented as String * either with one of the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isNotBetween("2002-12-17", "2002-12-18", false, false); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isNotBetween("2002-12-17", "2002-12-18", false, true); * assertThat(theTwoTowers.getReleaseDate()).isNotBetween("2002-12-18", "2002-12-19", true, false)</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @param inclusiveStart whether to include start date in period. * @param inclusiveEnd whether to include end date in period. * @return this assertion object. * @throws AssertionError if {@code actual} is {@code null}. * @throws NullPointerException if start Date as String is {@code null}. * @throws NullPointerException if end Date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is not in (start, end) period. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isNotBetween(String start, String end, boolean inclusiveStart, boolean inclusiveEnd) { return isNotBetween(parse(start), parse(end), inclusiveStart, inclusiveEnd); } /** * Verifies that the actual {@code Date} is not in [start, end[ period * <p> * Example: * <pre><code class='java'> SimpleDateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * // assertions will pass * assertThat(format.parse(&quot;1900-01-01&quot;)).isNotBetween(format.parse(&quot;2000-01-01&quot;), format.parse(&quot;2100-12-01&quot;)); * assertThat(format.parse(&quot;2200-01-01&quot;)).isNotBetween(format.parse(&quot;2000-01-01&quot;), format.parse(&quot;2100-12-01&quot;)); * assertThat(format.parse(&quot;2000-01-01&quot;)).isNotBetween(format.parse(&quot;1900-01-01&quot;), format.parse(&quot;2000-01-01&quot;)); * * // assertions will fail * assertThat(format.parse(&quot;2001-12-24&quot;)).isNotBetween(format.parse(&quot;2000-01-01&quot;), format.parse(&quot;2100-01-01&quot;)); * assertThat(format.parse(&quot;1900-01-01&quot;)).isNotBetween(format.parse(&quot;1900-01-01&quot;), format.parse(&quot;2000-01-01&quot;));</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start {@code Date} is {@code null}. * @throws NullPointerException if end {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is in [start, end[ period. */ public SELF isNotBetween(Date start, Date end) { return isNotBetween(start, end, true, false); } /** * Verifies that the actual {@code Date} is not in [start, end[ period * <p> * Example: * <pre><code class='java'> SimpleDateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); * // assertions will pass * assertThat(format.parse(&quot;1900-01-01&quot;)).isNotBetween(Instant.parse(&quot;2000-01-01T00:00:00Z&quot;), Instant.parse(&quot;2100-12-01T00:00:00Z&quot;)); * assertThat(format.parse(&quot;2200-01-01&quot;)).isNotBetween(Instant.parse(&quot;2000-01-01T00:00:00Z&quot;), Instant.parse(&quot;2100-12-01T00:00:00Z&quot;)); * assertThat(format.parse(&quot;2000-01-01&quot;)).isNotBetween(Instant.parse(&quot;1900-01-01T00:00:00Z&quot;), Instant.parse(&quot;2000-01-01T00:00:00Z&quot;)); * * // assertions will fail * assertThat(format.parse(&quot;2001-12-24&quot;)).isNotBetween(Instant.parse(&quot;2000-01-01T00:00:00Z&quot;), Instant.parse(&quot;2100-01-01T00:00:00Z&quot;)); * assertThat(format.parse(&quot;1900-01-01&quot;)).isNotBetween(Instant.parse(&quot;1900-01-01T00:00:00Z&quot;), Instant.parse(&quot;2000-01-01T00:00:00Z&quot;));</code></pre> * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start {@code Instant} is {@code null}. * @throws NullPointerException if end {@code Instant} is {@code null}. * @throws AssertionError if the actual {@code Date} is in [start, end[ period. * @since 3.19.0 */ public SELF isNotBetween(Instant start, Instant end) { return isNotBetween(dateFrom(start), dateFrom(end), true, false); } /** * Same assertion as {@link #isNotBetween(Date, Date)} but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(theFellowshipOfTheRing.getReleaseDate()).isNotBetween("2002-12-01", "2002-12-10"); * * // assertion will fail * assertThat(theFellowshipOfTheRing.getReleaseDate()).isNotBetween("2002-12-01", "2002-12-19")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param start the period start (inclusive), expected not to be null. * @param end the period end (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if start Date as String is {@code null}. * @throws NullPointerException if end Date as String is {@code null}. * @throws AssertionError if the actual {@code Date} is in [start, end[ period. * @throws AssertionError if one of the given date as String could not be converted to a Date. */ public SELF isNotBetween(String start, String end) { return isNotBetween(parse(start), parse(end), true, false); } /** * Verifies that the actual {@code Date} is strictly in the past. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(theTwoTowers.getReleaseDate()).isInThePast();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in the past. */ public SELF isInThePast() { dates.assertIsInThePast(info, actual); return myself; } /** * Verifies that the actual {@code Date} is today, that is matching current year, month and day (no check on hour, * minute, second, milliseconds). * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new Date()).isToday(); * * // assertion will fail * assertThat(theFellowshipOfTheRing.getReleaseDate()).isToday();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not today. */ public SELF isToday() { dates.assertIsToday(info, actual); return myself; } /** * Verifies that the actual {@code Date} is strictly in the future. * <p> * Example: * <pre><code class='java'> Date now = new Date(); * // assertion succeeds: * assertThat(new Date(now.getTime() + 1000)).isInTheFuture();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not in the future. */ public SELF isInTheFuture() { dates.assertIsInTheFuture(info, actual); return myself; } /** * Verifies that the actual {@code Date} is <b>strictly</b> before the given year. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isBeforeYear(2004); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isBeforeYear(2002); * assertThat(theTwoTowers.getReleaseDate()).isBeforeYear(2000);</code></pre> * * @param year the year to compare actual year to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} year is after or equals to the given year. */ public SELF isBeforeYear(int year) { dates.assertIsBeforeYear(info, actual, year); return myself; } /** * Verifies that the actual {@code Date} is <b>strictly</b> after the given year. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).isAfterYear(2001); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).isAfterYear(2002); * assertThat(theTwoTowers.getReleaseDate()).isAfterYear(2004);</code></pre> * * @param year the year to compare actual year to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} year is before or equals to the given year. */ public SELF isAfterYear(int year) { dates.assertIsAfterYear(info, actual, year); return myself; } /** * Verifies that the actual {@code Date} year is equal to the given year. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).hasYear(2002); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).hasYear(2004);</code></pre> * * @param year the year to compare actual year to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} year is not equal to the given year. */ public SELF hasYear(int year) { dates.assertHasYear(info, actual, year); return myself; } /** * Verifies that the actual {@code Date} month is equal to the given month, <b>month value starting at 1</b> * (January=1, February=2, ...). * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).hasMonth(12); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).hasMonth(10);</code></pre> * * @param month the month to compare actual month to, <b>month value starting at 1</b> (January=1, February=2, ...). * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} month is not equal to the given month. */ public SELF hasMonth(int month) { dates.assertHasMonth(info, actual, month); return myself; } /** * Verifies that the actual {@code Date} day of month is equal to the given day of month. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * // theTwoTowers release date : 2002-12-18 * assertThat(theTwoTowers.getReleaseDate()).hasDayOfMonth(18); * * // assertion will fail * assertThat(theTwoTowers.getReleaseDate()).hasDayOfMonth(20);</code></pre> * * @param dayOfMonth the day of month to compare actual day of month to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} month is not equal to the given day of month. */ public SELF hasDayOfMonth(int dayOfMonth) { dates.assertHasDayOfMonth(info, actual, dayOfMonth); return myself; } /** * Verifies that the actual {@code Date} day of week is equal to the given day of week (see * {@link Calendar#DAY_OF_WEEK} for valid values). * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasDayOfWeek(Calendar.SATURDAY); * * // assertion will fail * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasDayOfWeek(Calendar.MONDAY);</code></pre> * * @param dayOfWeek the day of week to compare actual day of week to, see {@link Calendar#DAY_OF_WEEK} for valid * values * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} week is not equal to the given day of week. */ public SELF hasDayOfWeek(int dayOfWeek) { dates.assertHasDayOfWeek(info, actual, dayOfWeek); return myself; } /** * Verifies that the actual {@code Date} hour of day is equal to the given hour of day (24-hour clock). * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasHourOfDay(13); * * // assertion will fail * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasHourOfDay(22);</code></pre> * * @param hourOfDay the hour of day to compare actual hour of day to (24-hour clock) * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} hour is not equal to the given hour. */ public SELF hasHourOfDay(int hourOfDay) { dates.assertHasHourOfDay(info, actual, hourOfDay); return myself; } /** * Verifies that the actual {@code Date} minute is equal to the given minute. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasMinute(20); * * // assertion will fail * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasMinute(17);</code></pre> * * @param minute the minute to compare actual minute to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} minute is not equal to the given minute. */ public SELF hasMinute(int minute) { dates.assertHasMinute(info, actual, minute); return myself; } /** * Verifies that the actual {@code Date} second is equal to the given second. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasSecond(35); * * // assertion will fail * assertThat(new Date(parseDatetime("2003-04-26T13:20:35").getTime()).hasSecond(11);</code></pre> * * @param second the second to compare actual second to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} second is not equal to the given second. */ public SELF hasSecond(int second) { dates.assertHasSecond(info, actual, second); return myself; } /** * Verifies that the actual {@code Date} millisecond is equal to the given millisecond. * <p> * Examples: * <pre><code class='java'> // assertion will pass * assertThat(parseDatetimeWithMs("2003-04-26T13:20:35.017")).hasMillisecond(17); * * // assertion will fail * assertThat(parseDatetimeWithMs("2003-04-26T13:20:35.017")).hasMillisecond(25);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param millisecond the millisecond to compare actual millisecond to * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} millisecond is not equal to the given millisecond. */ public SELF hasMillisecond(int millisecond) { dates.assertHasMillisecond(info, actual, millisecond); return myself; } /** * Verifies that actual and given {@code Date} are in the same year. * <p> * Example: * <pre><code class='java'> Date date1 = parse("2003-04-26"); * Date date2 = parse("2003-05-27"); * * assertThat(date1).isInSameYearAs(date2);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same year. */ public SELF isInSameYearAs(Date other) { dates.assertIsInSameYearAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} are in the same year. * <p> * Example: * <pre><code class='java'> Date date = parse("2003-04-26"); * Instant instant = Instant.parse("2003-04-26T12:30:00Z"); * * assertThat(date).isInSameYearAs(instant);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Instant} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same year. * @since 3.19.0 */ public SELF isInSameYearAs(Instant other) { dates.assertIsInSameYearAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameYearAs(Date)} but given date is represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> Date date1 = parse("2003-04-26"); * assertThat(date1).isInSameYearAs("2003-05-27")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given Date represented as String are not in the same year. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF isInSameYearAs(String dateAsString) { return isInSameYearAs(parse(dateAsString)); } /** * Verifies that actual and given {@code Date} have same month and year fields. * <p> * Example: * <pre><code class='java'> Date date1 = parse("2003-04-26"); * Date date2 = parse("2003-04-27"); * * assertThat(date1).isInSameMonthAs(date2);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same month and year. */ public SELF isInSameMonthAs(Date other) { dates.assertIsInSameMonthAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} have same month and year fields. * <p> * Example: * <pre><code class='java'> Date date = parse("2003-04-26"); * Instant instant = Instant.parse("2003-04-27T12:30:00Z"); * * assertThat(date).isInSameMonthAs(instant);</code></pre> * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Instant} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same month and year. * @since 3.19.0 */ public SELF isInSameMonthAs(Instant other) { dates.assertIsInSameMonthAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameMonthAs(Date)}but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> Date date1 = parse("2003-04-26"); * assertThat(date1).isInSameMonthAs("2003-04-27")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same month. */ public SELF isInSameMonthAs(String dateAsString) { return isInSameMonthAs(parse(dateAsString)); } /** * Verifies that actual and given {@code Date} have the same day of month, month and year fields values. * <p> * Example: * <pre><code class='java'> Date date1 = parseDatetime("2003-04-26T23:17:00"); * Date date2 = parseDatetime("2003-04-26T12:30:00"); * * assertThat(date1).isInSameDayAs(date2);</code></pre> * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same day, month and year. */ public SELF isInSameDayAs(Date other) { dates.assertIsInSameDayAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} have the same day of month, month and year fields values. * <p> * Example: * <pre><code class='java'> Date date = parseDatetime("2003-04-26T23:17:00"); * Instant instant = Instant.parse("2003-04-26T12:30:00Z"); * * assertThat(date).isInSameDayAs(instant);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same day, month and year. * @since 3.19.0 */ public SELF isInSameDayAs(Instant other) { dates.assertIsInSameDayAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameDayAs(Date)} but given date is represented as String either with one of the * supported default date formats or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> Date date1 = parseDatetime("2003-04-26T23:17:00"); * assertThat(date1).isInSameDayAs("2003-04-26")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * <p> * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same day of month. */ public SELF isInSameDayAs(String dateAsString) { return isInSameDayAs(parse(dateAsString)); } /** * Verifies that actual and given {@code Date} are chronologically in the same hour (i.e. their time difference &lt; 1 hour). * <p> * This assertion succeeds as time difference is exactly &lt; 1h: * <pre><code class='java'> Date date1 = parseDatetime("2003-04-26T13:00:00"); * Date date2 = parseDatetime("2003-04-26T13:30:00"); * assertThat(date1).isInSameHourWindowAs(date2);</code></pre> * * Two dates can have different hour fields and yet be in the same chronological hour, example: * <pre><code class='java'> Date date1 = parseDatetime("2003-04-26T13:00:00"); * Date date2 = parseDatetime("2003-04-26T12:59:59"); * // succeeds as time difference == 1s * assertThat(date1).isInSameHourWindowAs(date2);</code></pre> * * These assertions fail as time difference is equal to or greater than one hour: * <pre><code class='java'> Date date1 = parseDatetime("2003-04-26T13:00:00"); * Date date2 = parseDatetime("2003-04-26T14:00:01"); * Date date3 = parseDatetime("2003-04-26T14:00:00"); * assertThat(date1).isInSameHourWindowAs(date2); * assertThat(date1).isInSameHourWindowAs(date3);</code></pre> * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same hour. */ public SELF isInSameHourWindowAs(Date other) { dates.assertIsInSameHourWindowAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} are chronologically in the same hour (i.e. their time * difference &lt; 1 hour). * <p> * This assertion succeeds as time difference is exactly = 1h: * <pre><code class='java'> Date date = parseDatetime("2003-04-26T13:00:00Z"); * Instant instant = Instant.parse("2003-04-26T14:00:00Z"); * assertThat(date).isInSameHourWindowAs(instant);</code></pre> * * Two date/instant can have different hour fields and yet be in the same chronological hour, example: * <pre><code class='java'> Date date = parseDatetime("2003-04-26T13:00:00Z"); * Instant instant = Instant.parse("2003-04-26T12:59:59Z"); * // succeeds as time difference == 1s * assertThat(date).isInSameHourWindowAs(instant);</code></pre> * * These assertions fail as time difference is equal to or greater than one hour: * <pre><code class='java'> Date date = parseDatetime("2003-04-26T13:00:00Z"); * Instant instant = Instant.parse("2003-04-26T14:00:01Z"); * Instant instant2 = Instant.parse("2003-04-26T14:00:00Z"); * assertThat(date).isInSameHourWindowAs(instant); * assertThat(date).isInSameHourWindowAs(instant2);</code></pre> * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Instant} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same hour. * @since 3.19.0 */ public SELF isInSameHourWindowAs(Instant other) { dates.assertIsInSameHourWindowAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameHourWindowAs(java.util.Date)} but given date is represented as String either * with one of the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same day of month. */ public SELF isInSameHourWindowAs(String dateAsString) { return isInSameHourWindowAs(parse(dateAsString)); } /** * Verifies that actual and given {@code Date} are chronologically in the same minute (i.e. their time difference &lt; 1 * minute). * <p> * Example: * <pre><code class='java'> Date date1 = parseDatetime("2003-01-01T12:01:00"); * Date date2 = parseDatetime("2003-01-01T12:01:30"); * * // succeeds because date time difference &lt; 1 min * assertThat(date1).isInSameMinuteWindowAs(date2);</code></pre> * * Two dates can have different minute fields and yet be in the same chronological minute, example: * <pre><code class='java'> Date date1 = parseDatetime("2003-01-01T12:01:00"); * Date date3 = parseDatetime("2003-01-01T12:00:59"); * * // succeeds as time difference == 1s even though minute fields differ * assertThat(date1).isInSameMinuteWindowAs(date3);</code></pre> * * This assertion fails as time difference is &ge; 1 min: * <pre><code class='java'> Date date1 = parseDatetime("2003-01-01T12:01:00"); * Date date2 = parseDatetime("2003-01-01T12:02:00"); * assertThat(date1).isInSameMinuteWindowAs(date2);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same minute. */ public SELF isInSameMinuteWindowAs(Date other) { dates.assertIsInSameMinuteWindowAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} are chronologically in the same minute (i.e. their time difference &lt; 1 * minute). * <p> * Example: * <pre><code class='java'> Date date = parseDatetime("2003-01-01T12:01:00Z"); * Instant instant = Instant.parse("2003-01-01T12:01:30Z"); * * // succeeds because date time difference &lt; 1 min * assertThat(date).isInSameMinuteWindowAs(instant);</code></pre> * * Two date/instant can have different minute fields and yet be in the same chronological minute, example: * <pre><code class='java'> Date date = parseDatetime("2003-01-01T12:01:00Z"); * Instant instant = Instant.parse("2003-01-01T12:00:59Z"); * * // succeeds as time difference == 1s even though minute fields differ * assertThat(date).isInSameMinuteWindowAs(instant);</code></pre> * * This assertion fails as time difference is &ge; 1 min: * <pre><code class='java'> Date date = parseDatetime("2003-01-01T12:01:00Z"); * Instant instant = Instant.parse("2003-01-01T12:02:00Z"); * assertThat(date).isInSameMinuteWindowAs(instant);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Instant} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same minute. * @since 3.19.0 */ public SELF isInSameMinuteWindowAs(Instant other) { dates.assertIsInSameMinuteWindowAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameMinuteWindowAs(Date)} but given date is represented as String either with one of * the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same minute. */ public SELF isInSameMinuteWindowAs(String dateAsString) { return isInSameMinuteWindowAs(parse(dateAsString)); } /** * Verifies that actual and given {@code Date} are chronologically strictly in the same second (i.e. their time * difference &lt; 1 second). * <p> * Example: * <pre><code class='java'> Date date1 = parseDatetimeWithMs("2003-04-26T13:01:02.123"); * Date date2 = parseDatetimeWithMs("2003-04-26T13:01:02.456"); * * // succeeds as time difference is &lt; 1s * assertThat(date1).isInSameSecondWindowAs(date2);</code></pre> * * Two dates can have different second fields and yet be in the same chronological second, example: * <pre><code class='java'> Date date1 = parseDatetimeWithMs("2003-04-26T13:01:02.999"); * Date date2 = parseDatetimeWithMs("2003-04-26T13:01:03.000"); * * // succeeds as time difference is 1ms &lt; 1s * assertThat(date1).isInSameSecondWindowAs(date2);</code></pre> * * Those assertions fail as time difference is greater or equal to one second: * <pre><code class='java'> Date date1 = parseDatetimeWithMs("2003-04-26T13:01:01.000"); * Date date2 = parseDatetimeWithMs("2003-04-26T13:01:02.000"); * * // fails as time difference = 1s * assertThat(date1).isInSameSecondWindowAs(date2); * * Date date3 = parseDatetimeWithMs("2003-04-26T13:01:02.001"); * // fails as time difference &gt; 1s * assertThat(date1).isInSameSecondWindowAs(date3);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Date} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same second. */ public SELF isInSameSecondWindowAs(Date other) { dates.assertIsInSameSecondWindowAs(info, actual, other); return myself; } /** * Verifies that actual {@code Date} and given {@code Instant} are chronologically strictly in the same second (i.e. their time * difference &lt; 1 second). * <p> * Example: * <pre><code class='java'> Date date = parseDatetimeWithMs("2003-04-26T13:01:02.123Z"); * Instant instant = Instant.parse("2003-04-26T13:01:02.456Z"); * * // succeeds as time difference is &lt; 1s * assertThat(date).isInSameSecondWindowAs(instant);</code></pre> * * Two dates can have different second fields and yet be in the same chronological second, example: * <pre><code class='java'> Date date = parseDatetimeWithMs("2003-04-26T13:01:02.999Z"); * Instant instant = Instant.parse("2003-04-26T13:01:03.000Z"); * * // succeeds as time difference is 1ms &lt; 1s * assertThat(date).isInSameSecondWindowAs(instant);</code></pre> * * Those assertions fail as time difference is greater or equal to one second: * <pre><code class='java'> Date date = parseDatetimeWithMs("2003-04-26T13:01:01.000Z"); * Instant instant = Instant.parse("2003-04-26T13:01:02.000Z"); * * // fails as time difference = 1s * assertThat(date).isInSameSecondWindowAs(instant); * * Instant instant2 = Instant.parse("2003-04-26T13:01:02.001Z"); * // fails as time difference &gt; 1s * assertThat(date).isInSameSecondWindowAs(instant2);</code></pre> * * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * * @param other the given {@code Instant} to compare actual {@code Date} to. * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual {@code Date} and given {@code Instant} are not in the same second. * @since 3.19.0 */ public SELF isInSameSecondWindowAs(Instant other) { dates.assertIsInSameSecondWindowAs(info, actual, dateFrom(other)); return myself; } /** * Same assertion as {@link #isInSameSecondWindowAs(Date)} but given date is represented as String either with one of * the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String. * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if actual and given {@code Date} are not in the same second. */ public SELF isInSameSecondWindowAs(String dateAsString) { return isInSameSecondWindowAs(parse(dateAsString)); } /** * Verifies that the actual {@code Date} is close to the other date by less than delta (expressed in milliseconds), * if * difference is equal to delta it's ok. * <p> * One can use handy {@link TimeUnit} to convert a duration in milliseconds, for example you can express a delta of 5 * seconds with <code>TimeUnit.SECONDS.toMillis(5)</code>. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> Date date1 = new Date(); * Date date2 = new Date(date1.getTime() + 100); * * // assertion succeeds * assertThat(date1).isCloseTo(date2, 101) * .isCloseTo(date2, 100); * * // assertion fails * assertThat(date1).isCloseTo(date2, 80);</code></pre> * * @param other the date to compare actual to * @param deltaInMilliseconds the delta used for date comparison, expressed in milliseconds * @return this assertion object. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not close to the given date by less than delta. */ public SELF isCloseTo(Date other, long deltaInMilliseconds) { dates.assertIsCloseTo(info, actual, other, deltaInMilliseconds); return myself; } /** * Verifies that the actual {@code Date} is close to the given {@code Instant} by less than delta (expressed in milliseconds), * if the difference is equal to delta the assertion succeeds. * <p> * One can use handy {@link TimeUnit} to convert a duration in milliseconds, for example you can express a delta of 5 * seconds with <code>TimeUnit.SECONDS.toMillis(5)</code>. * <p> * Note that using a {@link #usingComparator(Comparator) custom comparator} has no effect on this assertion. * <p> * Example: * <pre><code class='java'> Date date = new Date(); * * // assertions succeed * assertThat(date).isCloseTo(date.toInstant().plusMillis(80), 80) * .isCloseTo(date.toInstant().plusMillis(80), 100); * * // assertions fails * assertThat(date).isCloseTo(date.toInstant().minusMillis(101), 100);</code></pre> * * @param other the Instant to compare actual to * @param deltaInMilliseconds the delta used for date comparison, expressed in milliseconds * @return this assertion object. * @throws NullPointerException if {@code Instant} parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not close to the given Instant by less than delta. * @since 3.19.0 */ public SELF isCloseTo(Instant other, long deltaInMilliseconds) { dates.assertIsCloseTo(info, actual, dateFrom(other), deltaInMilliseconds); return myself; } /** * Same assertion as {@link #isCloseTo(Date, long)} but given date is represented as String either with one of the * supported defaults date format or a user custom date format (set with method {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Default date formats (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given Date represented as String in default or custom date format. * @param deltaInMilliseconds the delta used for date comparison, expressed in milliseconds * @return this assertion object. * @throws NullPointerException if dateAsString parameter is {@code null}. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} is not close to the given date by less than delta. */ public SELF isCloseTo(String dateAsString, long deltaInMilliseconds) { return isCloseTo(parse(dateAsString), deltaInMilliseconds); } /** * Verifies that the actual {@code Date} has the same time as the given timestamp. * <p> * Both time or timestamp express a number of milliseconds since January 1, 1970, 00:00:00 GMT. * <p> * Example: * <pre><code class='java'> assertThat(new Date(42)).hasTime(42);</code></pre> * * @param timestamp the timestamp to compare actual time to. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} time is not equal to the given timestamp. * @see Date#getTime() */ public SELF hasTime(long timestamp) { dates.assertHasTime(info, actual, timestamp); return myself; } /** * Verifies that the actual {@code Date} has the same time as the given date, useful to compare {@link Date} and * {@link java.sql.Timestamp}. * <p> * Example: * <pre><code class='java'> Date date = new Date(); * Timestamp timestamp = new Timestamp(date.getTime()); * * // Fail as date is not an instance of Timestamp * assertThat(date).isEqualTo(timestamp); * * // Succeed as we compare date and timestamp time. * assertThat(date).hasSameTimeAs(timestamp);</code></pre> * * @param date the date to compare actual time to. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws AssertionError if the actual {@code Date} time is not equal to the given date time. * @throws NullPointerException if {@code Date} parameter is {@code null}. * @see Date#getTime() */ public SELF hasSameTimeAs(Date date) { dates.hasSameTimeAs(info, actual, date); return myself; } /** * Verifies that the actual {@code Date} represents the same time as the given date in {@code String} format. * <p> * It is the same assertion as {@link #hasSameTimeAs(Date)} but given date is represented as String either with one of * the supported default date formats or a user custom date format (set with method * {@link #withDateFormat(DateFormat)}). * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Example: * <pre><code class='java'> Date date = parseDatetime("2003-04-26T12:00:00"); * * // assertion will pass * assertThat(date).hasSameTimeAs("2003-04-26T12:00:00"); * * // assertion will fail * assertThat(date).hasSameTimeAs("2003-04-26T12:00:01"); * assertThat(date).hasSameTimeAs("2003-04-27T12:00:00")</code></pre> * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. * * @param dateAsString the given {@code Date} represented as {@code String} in default or custom date format. * @return this assertion object. * @throws AssertionError if the actual {@code Date} is {@code null}. * @throws NullPointerException if given date as String is {@code null}. * @throws AssertionError if the actual {@code Date} time is not equal to the time from date represented as * String. * @throws AssertionError if the given date as String could not be converted to a Date. */ public SELF hasSameTimeAs(String dateAsString) { dates.hasSameTimeAs(info, actual, parse(dateAsString)); return myself; } /** * Instead of using default date formats for the date String based Date assertions like {@link #isEqualTo(String)}, * AssertJ is going to use any date formats registered with one of these methods : * <ul> * <li>{@link #withDateFormat(String)}</li> * <li>this method</li> * <li>{@link #registerCustomDateFormat(java.text.DateFormat)}</li> * <li>{@link #registerCustomDateFormat(String)}</li> * </ul> * <p> * Beware that : * <ul> * <li>this will be the case for <b>all future Date assertions in the test suite</b></li> * <li>once a custom date format is registered, the default date formats are not used anymore</li> * </ul> * <p> * To revert to default format, call {@link #useDefaultDateFormatsOnly()} or {@link #withDefaultDateFormatsOnly()}. * * @param userCustomDateFormat the new Date format used for String based Date assertions. * @return this assertion object. */ @CheckReturnValue public SELF withDateFormat(DateFormat userCustomDateFormat) { registerCustomDateFormat(userCustomDateFormat); return myself; } /** * Instead of using default date formats for the date String based Date assertions like {@link #isEqualTo(String)}, * AssertJ is going to use any date formats registered with one of these methods : * <ul> * <li>this method</li> * <li>{@link #withDateFormat(java.text.DateFormat)}</li> * <li>{@link #registerCustomDateFormat(java.text.DateFormat)}</li> * <li>{@link #registerCustomDateFormat(String)}</li> * </ul> * <p> * Beware that : * <ul> * <li>this will be the case for <b>all future Date assertions in the test suite</b></li> * <li>once a custom date format is registered, the default date formats are not used anymore</li> * </ul> * <p> * To revert to default format, call {@link #useDefaultDateFormatsOnly()} or {@link #withDefaultDateFormatsOnly()}. * * @param userCustomDateFormatPattern the new Date format string pattern used for String based Date assertions. * @return this assertion object. */ @CheckReturnValue public SELF withDateFormat(String userCustomDateFormatPattern) { requireNonNull(userCustomDateFormatPattern, DATE_FORMAT_PATTERN_SHOULD_NOT_BE_NULL); return withDateFormat(new SimpleDateFormat(userCustomDateFormatPattern)); } /** * Instead of using default strict date/time parsing, it is possible to use lenient parsing mode for default date * formats parser to interpret inputs that do not precisely match supported date formats (lenient parsing). * <p> * With strict parsing, inputs must match exactly date/time formats. * <p> * Example: * <pre><code class='java'> final Date date = Dates.parse("2001-02-03"); * final Date dateTime = parseDatetime("2001-02-03T04:05:06"); * final Date dateTimeWithMs = parseDatetimeWithMs("2001-02-03T04:05:06.700"); * * AbstractDateAssert.setLenientDateParsing(true); * * // assertions will pass * assertThat(date).isEqualTo("2001-02-03"); * assertThat(date).isEqualTo("2001-02-02T24:00:00"); * assertThat(date).isEqualTo("2001-02-04T-24:00:00.000"); * assertThat(dateTime).isEqualTo("2001-02-03T04:05:05.1000"); * assertThat(dateTime).isEqualTo("2001-02-03T04:04:66"); * assertThat(dateTimeWithMs).isEqualTo("2001-02-03T04:05:07.-300"); * * // assertions will fail * assertThat(date).hasSameTimeAs("2001-02-04"); // different date * assertThat(dateTime).hasSameTimeAs("2001-02-03 04:05:06"); // leniency does not help here</code></pre> * * To revert to default strict date parsing, call {@code setLenientDateParsing(false)}. * * @param lenientDateParsing whether lenient parsing mode should be enabled or not */ public static void setLenientDateParsing(boolean lenientDateParsing) { lenientParsing = lenientDateParsing; } /** * Add the given date format to the ones used to parse date String in String based Date assertions like * {@link #isEqualTo(String)}. * <p> * User date formats are used before default ones in the order they have been registered (first registered, first * used). * <p> * AssertJ is going to use any date formats registered with one of these methods : * <ul> * <li>{@link #withDateFormat(String)}</li> * <li>{@link #withDateFormat(java.text.DateFormat)}</li> * <li>this method</li> * <li>{@link #registerCustomDateFormat(String)}</li> * </ul> * <p> * Beware that AssertJ will use the newly registered format for <b>all remaining Date assertions in the test suite</b> * <p> * To revert to default formats only, call {@link #useDefaultDateFormatsOnly()} or * {@link #withDefaultDateFormatsOnly()}. * <p> * Code examples: * <pre><code class='java'> Date date = ... // set to 2003 April the 26th * assertThat(date).isEqualTo("2003-04-26"); * * try { * // date with a custom format : failure since the default formats don't match. * assertThat(date).isEqualTo("2003/04/26"); * } catch (AssertionError e) { * assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + * "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); * } * * // registering a custom date format to make the assertion pass * registerCustomDateFormat(new SimpleDateFormat("yyyy/MM/dd")); // registerCustomDateFormat("yyyy/MM/dd") would work to. * assertThat(date).isEqualTo("2003/04/26"); * * // the default formats are still available and should work * assertThat(date).isEqualTo("2003-04-26");</code></pre> * * @param userCustomDateFormat the new Date format used for String based Date assertions. */ public static void registerCustomDateFormat(DateFormat userCustomDateFormat) { ConfigurationProvider.loadRegisteredConfiguration(); requireNonNull(userCustomDateFormat, DATE_FORMAT_SHOULD_NOT_BE_NULL); userDateFormats.get().add(userCustomDateFormat); } /** * Add the given date format to the ones used to parse date String in String based Date assertions like * {@link #isEqualTo(String)}. * <p> * User date formats are used before default ones in the order they have been registered (first registered, first * used). * <p> * AssertJ is going to use any date formats registered with one of these methods: * <ul> * <li>{@link #withDateFormat(String)}</li> * <li>{@link #withDateFormat(java.text.DateFormat)}</li> * <li>{@link #registerCustomDateFormat(java.text.DateFormat)}</li> * <li>this method</li> * </ul> * <p> * Beware that AssertJ will use the newly registered format for <b>all remaining Date assertions in the test suite</b> * <p> * To revert to default formats only, call {@link #useDefaultDateFormatsOnly()} or * {@link #withDefaultDateFormatsOnly()}. * <p> * Code examples: * <pre><code class='java'> Date date = ... // set to 2003 April the 26th * assertThat(date).isEqualTo("2003-04-26"); * * try { * // date with a custom format : failure since the default formats don't match. * assertThat(date).isEqualTo("2003/04/26"); * } catch (AssertionError e) { * assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + * "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); * } * * // registering a custom date format to make the assertion pass * registerCustomDateFormat("yyyy/MM/dd"); * assertThat(date).isEqualTo("2003/04/26"); * * // the default formats are still available and should work * assertThat(date).isEqualTo("2003-04-26");</code></pre> * * @param userCustomDateFormatPattern the new Date format pattern used for String based Date assertions. */ public static void registerCustomDateFormat(String userCustomDateFormatPattern) { requireNonNull(userCustomDateFormatPattern, DATE_FORMAT_PATTERN_SHOULD_NOT_BE_NULL); registerCustomDateFormat(new SimpleDateFormat(userCustomDateFormatPattern)); } /** * Remove all registered custom date formats =&gt; use only the defaults date formats to parse string as date. * <p> * User custom date format take precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * <p> * If you are getting an {@code IllegalArgumentException} with <i>"Unknown pattern character 'X'"</i> message (some Android versions don't support it), * you can explicitly specify the date format to use so that the default ones are bypassed. */ public static void useDefaultDateFormatsOnly() { userDateFormats.get().clear(); } /** * Remove all registered custom date formats =&gt; use only the default date formats to parse string as date. * <p> * User custom date format takes precedence over the default ones. * <p> * Unless specified otherwise, beware that the default formats are expressed in the current local timezone. * <p> * Defaults date format (expressed in the local time zone unless specified otherwise) are: * <ul> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd HH:mm:ss.SSS</code></li> * <li><code>yyyy-MM-dd'T'HH:mm:ssX</code> (in ISO Time zone)</li> * <li><code>yyyy-MM-dd'T'HH:mm:ss</code></li> * <li><code>yyyy-MM-dd</code></li> * </ul> * <p> * Example of valid string date representations: * <ul> * <li><code>2003-04-26T03:01:02.758+00:00</code></li> * <li><code>2003-04-26T03:01:02.999</code></li> * <li><code>2003-04-26 03:01:02.999</code></li> * <li><code>2003-04-26T03:01:02+00:00</code></li> * <li><code>2003-04-26T13:01:02</code></li> * <li><code>2003-04-26</code></li> * </ul> * * @return this assertion */ @CheckReturnValue public SELF withDefaultDateFormatsOnly() { useDefaultDateFormatsOnly(); return myself; } /** * Thread safe utility method to parse a Date with {@link #userDateFormats} first, then {@link #defaultDateFormats()}. * <p> * Returns <code>null</code> if dateAsString parameter is <code>null</code>. * * @param dateAsString the string to parse as a Date with {@link #userDateFormats} * @return the corresponding Date, null if dateAsString parameter is null. * @throws AssertionError if the string can't be parsed as a Date */ // TODO reduce the visibility of the fields annotated with @VisibleForTesting Date parse(String dateAsString) { if (dateAsString == null) return null; // parse with date format specified by user if any, otherwise use default formats // no synchronization needed as userCustomDateFormat is thread local Date date = parseDateWith(dateAsString, userDateFormats.get()); if (date != null) return date; // no matching user date format, let's try default format date = parseDateWithDefaultDateFormats(dateAsString); if (date != null) return date; // no matching date format, throw an error throw new AssertionError("Failed to parse %s with any of these date formats:%n %s".formatted(dateAsString, info.representation() .toStringOf(dateFormatsInOrderOfUsage()))); } private Date parseDateWithDefaultDateFormats(final String dateAsString) { return parseDateWith(dateAsString, defaultDateFormats()); } private List<DateFormat> dateFormatsInOrderOfUsage() { List<DateFormat> allDateFormatsInOrderOfUsage = newArrayList(userDateFormats.get()); allDateFormatsInOrderOfUsage.addAll(defaultDateFormats()); return allDateFormatsInOrderOfUsage; } private Date parseDateWith(final String dateAsString, final Collection<DateFormat> dateFormats) { for (DateFormat defaultDateFormat : dateFormats) { try { return defaultDateFormat.parse(dateAsString); } catch (@SuppressWarnings("unused") ParseException e) { // ignore and try next date format } } return null; } private static <T> Date[] toDateArray(T[] values, Function<T, Date> converter) { Date[] dates = new Date[values.length]; for (int i = 0; i < values.length; i++) { dates[i] = converter.apply(values[i]); } return dates; } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super Date> customComparator) { return usingComparator(customComparator, null); } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super Date> customComparator, String customComparatorDescription) { this.dates = new Dates(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription)); return super.usingComparator(customComparator, customComparatorDescription); } @Override @CheckReturnValue public SELF usingDefaultComparator() { this.dates = Dates.instance(); return super.usingDefaultComparator(); } private Date dateFrom(Instant instant) { return actual instanceof Timestamp ? Timestamp.from(instant) : Date.from(instant); } }
AbstractDateAssert
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
{ "start": 12158, "end": 13764 }
class ____ the specified object will be considered. * * @param target * the object to reflect, must not be {@code null}. * @param fieldName * the field name to obtain. * @param forceAccess * whether to break scope restrictions using the * {@link AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match public fields. * @return the Field object. * @throws NullPointerException * if {@code target} is {@code null}. * @throws IllegalArgumentException * if {@code fieldName} is {@code null}, blank or empty, or could not be found. * @throws IllegalAccessException * if the field is not made accessible. * @throws SecurityException if an underlying accessible object's method denies the request. * @see SecurityManager#checkPermission */ public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException { Objects.requireNonNull(target, "target"); final Class<?> cls = target.getClass(); final Field field = getDeclaredField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName); // already forced access above, don't repeat it here: return readField(field, target, false); } /** * Gets the value of a {@code static} {@link Field} by name. The field must be {@code public}. Only the specified *
of
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/operators/base/PartitionOperatorBase.java
{ "start": 1743, "end": 4547 }
enum ____ { REBALANCE, HASH, RANGE, CUSTOM; } // -------------------------------------------------------------------------------------------- private final PartitionMethod partitionMethod; private Partitioner<?> customPartitioner; private DataDistribution distribution; private Ordering ordering; public PartitionOperatorBase( UnaryOperatorInformation<IN, IN> operatorInfo, PartitionMethod pMethod, int[] keys, String name) { super( new UserCodeObjectWrapper<NoOpFunction>(new NoOpFunction()), operatorInfo, keys, name); this.partitionMethod = pMethod; } public PartitionOperatorBase( UnaryOperatorInformation<IN, IN> operatorInfo, PartitionMethod pMethod, String name) { super(new UserCodeObjectWrapper<NoOpFunction>(new NoOpFunction()), operatorInfo, name); this.partitionMethod = pMethod; } // -------------------------------------------------------------------------------------------- public PartitionMethod getPartitionMethod() { return this.partitionMethod; } public Partitioner<?> getCustomPartitioner() { return customPartitioner; } public DataDistribution getDistribution() { return this.distribution; } public void setOrdering(Ordering ordering) { this.ordering = ordering; } public Ordering getOrdering() { return ordering; } public void setDistribution(DataDistribution distribution) { this.distribution = distribution; } public void setCustomPartitioner(Partitioner<?> customPartitioner) { if (customPartitioner != null) { int[] keys = getKeyColumns(0); if (keys == null || keys.length == 0) { throw new IllegalArgumentException( "Cannot use custom partitioner for a non-grouped GroupReduce (AllGroupReduce)"); } if (keys.length > 1) { throw new IllegalArgumentException( "Cannot use the key partitioner for composite keys (more than one key field)"); } } this.customPartitioner = customPartitioner; } @Override public SingleInputSemanticProperties getSemanticProperties() { return new SingleInputSemanticProperties.AllFieldsForwardedProperties(); } // -------------------------------------------------------------------------------------------- @Override protected List<IN> executeOnCollections( List<IN> inputData, RuntimeContext runtimeContext, ExecutionConfig executionConfig) { return inputData; } }
PartitionMethod
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/FileSystemOutputFormat.java
{ "start": 1923, "end": 8703 }
class ____<T> implements OutputFormat<T>, FinalizeOnMaster, Serializable, SupportsConcurrentExecutionAttempts { private static final long serialVersionUID = 1L; private final FileSystemFactory fsFactory; private final TableMetaStoreFactory msFactory; private final boolean overwrite; private final boolean isToLocal; private final Path stagingPath; private final String[] partitionColumns; private final boolean dynamicGrouped; private final LinkedHashMap<String, String> staticPartitions; private final PartitionComputer<T> computer; private final OutputFormatFactory<T> formatFactory; private final OutputFileConfig outputFileConfig; private final ObjectIdentifier identifier; private final PartitionCommitPolicyFactory partitionCommitPolicyFactory; private transient PartitionWriter<T> writer; private transient Configuration parameters; private FileSystemOutputFormat( FileSystemFactory fsFactory, TableMetaStoreFactory msFactory, boolean overwrite, boolean isToLocal, Path stagingPath, String[] partitionColumns, boolean dynamicGrouped, LinkedHashMap<String, String> staticPartitions, OutputFormatFactory<T> formatFactory, PartitionComputer<T> computer, OutputFileConfig outputFileConfig, ObjectIdentifier identifier, PartitionCommitPolicyFactory partitionCommitPolicyFactory) { this.fsFactory = fsFactory; this.msFactory = msFactory; this.overwrite = overwrite; this.isToLocal = isToLocal; this.stagingPath = stagingPath; this.partitionColumns = partitionColumns; this.dynamicGrouped = dynamicGrouped; this.staticPartitions = staticPartitions; this.formatFactory = formatFactory; this.computer = computer; this.outputFileConfig = outputFileConfig; this.identifier = identifier; this.partitionCommitPolicyFactory = partitionCommitPolicyFactory; createStagingDirectory(this.stagingPath); } private static void createStagingDirectory(Path stagingPath) { try { final FileSystem stagingFileSystem = stagingPath.getFileSystem(); Preconditions.checkState( !stagingFileSystem.exists(stagingPath), "Staging dir %s already exists", stagingPath); stagingFileSystem.mkdirs(stagingPath); } catch (IOException e) { throw new RuntimeException( "An IO error occurred while accessing the staging FileSystem.", e); } } @Override public void finalizeGlobal(FinalizationContext context) { try { List<PartitionCommitPolicy> policies = Collections.emptyList(); if (partitionCommitPolicyFactory != null) { policies = partitionCommitPolicyFactory.createPolicyChain( Thread.currentThread().getContextClassLoader(), () -> { try { return fsFactory.create(stagingPath.toUri()); } catch (IOException e) { throw new RuntimeException(e); } }); } FileSystemCommitter committer = new FileSystemCommitter( fsFactory, msFactory, overwrite, stagingPath, partitionColumns.length, isToLocal, identifier, staticPartitions, policies); committer.commitPartitions( (subtaskIndex, attemptNumber) -> { try { if (context.getFinishedAttempt(subtaskIndex) == attemptNumber) { return true; } } catch (IllegalArgumentException ignored) { // maybe met a dir or file which does not belong to this job } return false; }); } catch (Exception e) { throw new TableException("Exception in finalizeGlobal", e); } finally { try { fsFactory.create(stagingPath.toUri()).delete(stagingPath, true); } catch (IOException ignore) { } } } @Override public void configure(Configuration parameters) { this.parameters = parameters; } @Override public void open(InitializationContext context) throws IOException { try { PartitionTempFileManager fileManager = new PartitionTempFileManager( fsFactory, stagingPath, context.getTaskNumber(), context.getAttemptNumber(), outputFileConfig); PartitionWriter.Context<T> writerContext = new PartitionWriter.Context<>(parameters, formatFactory); writer = PartitionWriterFactory.<T>get( partitionColumns.length - staticPartitions.size() > 0, dynamicGrouped, staticPartitions) .create( writerContext, fileManager, computer, new PartitionWriter.DefaultPartitionWriterListener()); } catch (Exception e) { throw new TableException("Exception in open", e); } } @Override public void writeRecord(T record) { try { writer.write(record); } catch (Exception e) { throw new TableException("Exception in writeRecord", e); } } @Override public void close() throws IOException { try { if (writer != null) { writer.close(); } } catch (Exception e) { throw new TableException("Exception in close", e); } } /** Builder to build {@link FileSystemOutputFormat}. */ public static
FileSystemOutputFormat
java
elastic__elasticsearch
modules/data-streams/src/main/java/org/elasticsearch/datastreams/DataStreamsPlugin.java
{ "start": 6823, "end": 17965 }
class ____ extends Plugin implements ActionPlugin, HealthPlugin { public static final Setting<TimeValue> TIME_SERIES_POLL_INTERVAL = Setting.timeSetting( "time_series.poll_interval", TimeValue.timeValueMinutes(5), TimeValue.timeValueMinutes(1), TimeValue.timeValueMinutes(10), Setting.Property.NodeScope, Setting.Property.Dynamic ); private static final TimeValue MAX_LOOK_AHEAD_TIME = TimeValue.timeValueHours(2); public static final Setting<TimeValue> LOOK_AHEAD_TIME = Setting.timeSetting( "index.look_ahead_time", TimeValue.timeValueMinutes(30), TimeValue.timeValueMinutes(1), TimeValue.timeValueDays(7), // is effectively 2h now. Setting.Property.IndexScope, Setting.Property.Dynamic, Setting.Property.ServerlessPublic ); /** * Returns the look ahead time and lowers it when it to 2 hours if it is configured to more than 2 hours. */ public static TimeValue getLookAheadTime(Settings settings) { TimeValue lookAheadTime = DataStreamsPlugin.LOOK_AHEAD_TIME.get(settings); if (lookAheadTime.compareTo(DataStreamsPlugin.MAX_LOOK_AHEAD_TIME) > 0) { lookAheadTime = DataStreamsPlugin.MAX_LOOK_AHEAD_TIME; } return lookAheadTime; } public static final String LIFECYCLE_CUSTOM_INDEX_METADATA_KEY = "data_stream_lifecycle"; public static final Setting<TimeValue> LOOK_BACK_TIME = Setting.timeSetting( "index.look_back_time", TimeValue.timeValueHours(2), TimeValue.timeValueMinutes(1), TimeValue.timeValueDays(7), Setting.Property.IndexScope, Setting.Property.Dynamic, Setting.Property.ServerlessPublic ); // The dependency of index.look_ahead_time is a cluster setting and currently there is no clean validation approach for this: private final SetOnce<UpdateTimeSeriesRangeService> updateTimeSeriesRangeService = new SetOnce<>(); private final SetOnce<DataStreamLifecycleErrorStore> errorStoreInitialisationService = new SetOnce<>(); private final SetOnce<DataStreamLifecycleService> dataLifecycleInitialisationService = new SetOnce<>(); private final SetOnce<DataStreamLifecycleHealthInfoPublisher> dataStreamLifecycleErrorsPublisher = new SetOnce<>(); private final SetOnce<DataStreamLifecycleHealthIndicatorService> dataStreamLifecycleHealthIndicatorService = new SetOnce<>(); private final Settings settings; public DataStreamsPlugin(Settings settings) { this.settings = settings; } protected Clock getClock() { return Clock.systemUTC(); } static void additionalLookAheadTimeValidation(TimeValue lookAhead, TimeValue timeSeriesPollInterval) { if (lookAhead.compareTo(timeSeriesPollInterval) < 0) { final String message = String.format( Locale.ROOT, "failed to parse value%s for setting [%s], must be lower than setting [%s] which is [%s]", " [" + lookAhead.getStringRep() + "]", LOOK_AHEAD_TIME.getKey(), TIME_SERIES_POLL_INTERVAL.getKey(), timeSeriesPollInterval.getStringRep() ); throw new IllegalArgumentException(message); } } @Override public List<Setting<?>> getSettings() { List<Setting<?>> pluginSettings = new ArrayList<>(); pluginSettings.add(TIME_SERIES_POLL_INTERVAL); pluginSettings.add(LOOK_AHEAD_TIME); pluginSettings.add(LOOK_BACK_TIME); pluginSettings.add(DataStreamLifecycleService.DATA_STREAM_LIFECYCLE_POLL_INTERVAL_SETTING); pluginSettings.add(DataStreamLifecycleService.DATA_STREAM_MERGE_POLICY_TARGET_FLOOR_SEGMENT_SETTING); pluginSettings.add(DataStreamLifecycleService.DATA_STREAM_MERGE_POLICY_TARGET_FACTOR_SETTING); pluginSettings.add(DataStreamLifecycleService.DATA_STREAM_SIGNALLING_ERROR_RETRY_INTERVAL_SETTING); return pluginSettings; } @Override public Collection<?> createComponents(PluginServices services) { Collection<Object> components = new ArrayList<>(); var updateTimeSeriesRangeService = new UpdateTimeSeriesRangeService( services.environment().settings(), services.threadPool(), services.clusterService() ); this.updateTimeSeriesRangeService.set(updateTimeSeriesRangeService); components.add(this.updateTimeSeriesRangeService.get()); errorStoreInitialisationService.set(new DataStreamLifecycleErrorStore(services.threadPool()::absoluteTimeInMillis)); dataStreamLifecycleErrorsPublisher.set( new DataStreamLifecycleHealthInfoPublisher( settings, services.client(), services.clusterService(), errorStoreInitialisationService.get() ) ); dataLifecycleInitialisationService.set( new DataStreamLifecycleService( settings, new OriginSettingClient(services.client(), DATA_STREAM_LIFECYCLE_ORIGIN), services.clusterService(), getClock(), services.threadPool(), services.threadPool()::absoluteTimeInMillis, errorStoreInitialisationService.get(), services.allocationService(), dataStreamLifecycleErrorsPublisher.get(), services.dataStreamGlobalRetentionSettings() ) ); dataLifecycleInitialisationService.get().init(); dataStreamLifecycleHealthIndicatorService.set(new DataStreamLifecycleHealthIndicatorService(services.projectResolver())); components.add(errorStoreInitialisationService.get()); components.add(dataLifecycleInitialisationService.get()); components.add(dataStreamLifecycleErrorsPublisher.get()); return components; } @Override public List<ActionHandler> getActions() { List<ActionHandler> actions = new ArrayList<>(); actions.add(new ActionHandler(CreateDataStreamAction.INSTANCE, TransportCreateDataStreamAction.class)); actions.add(new ActionHandler(DeleteDataStreamAction.INSTANCE, TransportDeleteDataStreamAction.class)); actions.add(new ActionHandler(GetDataStreamAction.INSTANCE, TransportGetDataStreamsAction.class)); actions.add(new ActionHandler(DataStreamsStatsAction.INSTANCE, TransportDataStreamsStatsAction.class)); actions.add(new ActionHandler(MigrateToDataStreamAction.INSTANCE, TransportMigrateToDataStreamAction.class)); actions.add(new ActionHandler(PromoteDataStreamAction.INSTANCE, TransportPromoteDataStreamAction.class)); actions.add(new ActionHandler(ModifyDataStreamsAction.INSTANCE, TransportModifyDataStreamsAction.class)); actions.add(new ActionHandler(PutDataStreamLifecycleAction.INSTANCE, TransportPutDataStreamLifecycleAction.class)); actions.add(new ActionHandler(GetDataStreamLifecycleAction.INSTANCE, TransportGetDataStreamLifecycleAction.class)); actions.add(new ActionHandler(DeleteDataStreamLifecycleAction.INSTANCE, TransportDeleteDataStreamLifecycleAction.class)); actions.add(new ActionHandler(ExplainDataStreamLifecycleAction.INSTANCE, TransportExplainDataStreamLifecycleAction.class)); actions.add(new ActionHandler(GetDataStreamLifecycleStatsAction.INSTANCE, TransportGetDataStreamLifecycleStatsAction.class)); actions.add(new ActionHandler(GetDataStreamOptionsAction.INSTANCE, TransportGetDataStreamOptionsAction.class)); actions.add(new ActionHandler(PutDataStreamOptionsAction.INSTANCE, TransportPutDataStreamOptionsAction.class)); actions.add(new ActionHandler(DeleteDataStreamOptionsAction.INSTANCE, TransportDeleteDataStreamOptionsAction.class)); actions.add(new ActionHandler(GetDataStreamSettingsAction.INSTANCE, TransportGetDataStreamSettingsAction.class)); actions.add(new ActionHandler(UpdateDataStreamSettingsAction.INSTANCE, TransportUpdateDataStreamSettingsAction.class)); actions.add(new ActionHandler(GetDataStreamMappingsAction.INSTANCE, TransportGetDataStreamMappingsAction.class)); actions.add(new ActionHandler(UpdateDataStreamMappingsAction.INSTANCE, TransportUpdateDataStreamMappingsAction.class)); return actions; } @Override public List<RestHandler> getRestHandlers( Settings settings, NamedWriteableRegistry namedWriteableRegistry, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster, Predicate<NodeFeature> clusterSupportsFeature ) { indexScopedSettings.addSettingsUpdateConsumer(LOOK_AHEAD_TIME, value -> { TimeValue timeSeriesPollInterval = updateTimeSeriesRangeService.get().pollInterval; additionalLookAheadTimeValidation(value, timeSeriesPollInterval); }); List<RestHandler> handlers = new ArrayList<>(); handlers.add(new RestCreateDataStreamAction()); handlers.add(new RestDeleteDataStreamAction()); handlers.add(new RestGetDataStreamsAction()); handlers.add(new RestDataStreamsStatsAction()); handlers.add(new RestMigrateToDataStreamAction()); handlers.add(new RestPromoteDataStreamAction()); handlers.add(new RestModifyDataStreamsAction()); handlers.add(new RestPutDataStreamLifecycleAction()); handlers.add(new RestGetDataStreamLifecycleAction()); handlers.add(new RestDeleteDataStreamLifecycleAction()); handlers.add(new RestExplainDataStreamLifecycleAction()); handlers.add(new RestDataStreamLifecycleStatsAction()); handlers.add(new RestGetDataStreamOptionsAction()); handlers.add(new RestPutDataStreamOptionsAction()); handlers.add(new RestDeleteDataStreamOptionsAction()); handlers.add(new RestGetDataStreamSettingsAction()); handlers.add(new RestUpdateDataStreamSettingsAction()); handlers.add(new RestGetDataStreamMappingsAction()); handlers.add(new RestUpdateDataStreamMappingsAction()); return handlers; } @Override public Collection<IndexSettingProvider> getAdditionalIndexSettingProviders(IndexSettingProvider.Parameters parameters) { return List.of(new DataStreamIndexSettingsProvider(parameters.mapperServiceFactory())); } @Override public void close() throws IOException { try { IOUtils.close(dataLifecycleInitialisationService.get()); } catch (IOException e) { throw new ElasticsearchException("unable to close the data stream lifecycle service", e); } } @Override public Collection<HealthIndicatorService> getHealthIndicatorServices() { return List.of(dataStreamLifecycleHealthIndicatorService.get()); } }
DataStreamsPlugin
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java
{ "start": 1663, "end": 6192 }
class ____ { TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A"); @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void contextIsClearedAfterChainProceeds() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); filter.doFilter(request, response, chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd", "ROLE_B"); final SecurityContext scBefore = new SecurityContextImpl(); final SecurityContext scExpectedAfter = new SecurityContextImpl(); scExpectedAfter.setAuthentication(this.testToken); scBefore.setAuthentication(beforeAuth); final SecurityContextRepository repo = mock(SecurityContextRepository.class); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo); given(repo.loadContext(any(HttpRequestResponseHolder.class))).willReturn(scBefore); final FilterChain chain = (request1, response1) -> { assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth); // Change the context here SecurityContextHolder.setContext(scExpectedAfter); }; filter.doFilter(request, response, chain); verify(repo).saveContext(scExpectedAfter, request, response); } @Test public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter( mock(SecurityContextRepository.class)); request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); } @Test public void sessionIsEagerlyCreatedWhenConfigured() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); filter.setForceEagerSessionCreation(true); filter.doFilter(request, response, chain); assertThat(request.getSession(false)).isNotNull(); } @Test public void nullSecurityContextRepoDoesntSaveContextOrCreateSession() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextRepository repo = new NullSecurityContextRepository(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo); filter.doFilter(request, response, chain); assertThat(repo.containsContext(request)).isFalse(); assertThat(request.getSession(false)).isNull(); } }
SecurityContextPersistenceFilterTests
java
spring-projects__spring-framework
spring-jdbc/src/test/java/org/springframework/jdbc/object/CustomerMapper.java
{ "start": 824, "end": 1190 }
class ____ implements RowMapper<Customer> { private static final String[] COLUMN_NAMES = new String[] {"id", "forename"}; @Override public Customer mapRow(ResultSet rs, int rownum) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; } }
CustomerMapper
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/InferTrainedModelDeploymentRequestsTests.java
{ "start": 788, "end": 3191 }
class ____ extends AbstractWireSerializingTestCase<InferTrainedModelDeploymentAction.Request> { @Override protected Writeable.Reader<InferTrainedModelDeploymentAction.Request> instanceReader() { return InferTrainedModelDeploymentAction.Request::new; } @Override protected InferTrainedModelDeploymentAction.Request createTestInstance() { boolean createQueryStringRequest = randomBoolean(); InferTrainedModelDeploymentAction.Request request; if (createQueryStringRequest) { request = InferTrainedModelDeploymentAction.Request.forTextInput( randomAlphaOfLength(4), randomBoolean() ? null : InferModelActionRequestTests.randomInferenceConfigUpdate(), Arrays.asList(generateRandomStringArray(4, 7, false)), randomBoolean() ? null : randomTimeValue() ); } else { List<Map<String, Object>> docs = randomList( 5, () -> randomMap(1, 3, () -> Tuple.tuple(randomAlphaOfLength(7), randomAlphaOfLength(7))) ); request = InferTrainedModelDeploymentAction.Request.forDocs( randomAlphaOfLength(4), randomBoolean() ? null : InferModelActionRequestTests.randomInferenceConfigUpdate(), docs, randomBoolean() ? null : randomTimeValue() ); } request.setHighPriority(randomBoolean()); request.setPrefixType(randomFrom(TrainedModelPrefixStrings.PrefixType.values())); request.setChunkResults(randomBoolean()); return request; } @Override protected InferTrainedModelDeploymentAction.Request mutateInstance(InferTrainedModelDeploymentAction.Request instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { List<NamedWriteableRegistry.Entry> entries = new ArrayList<>(new MlInferenceNamedXContentProvider().getNamedWriteables()); return new NamedWriteableRegistry(entries); } public void testTimeoutNotNull() { assertNotNull(createTestInstance().getInferenceTimeout()); } public void testTimeoutNull() { assertNull(createTestInstance().getTimeout()); } }
InferTrainedModelDeploymentRequestsTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/TimeSeries.java
{ "start": 1008, "end": 4249 }
class ____ implements Writeable, ToXContentFragment { public final long fiveMinutes; public final long fifteenMinutes; public final long twentyFourHours; public final long total; public TimeSeries(long total) { this.fiveMinutes = 0; this.fifteenMinutes = 0; this.twentyFourHours = 0; this.total = total; } public TimeSeries(long fiveMinutes, long fifteenMinutes, long twentyFourHours, long total) { this.fiveMinutes = fiveMinutes; this.fifteenMinutes = fifteenMinutes; this.twentyFourHours = twentyFourHours; this.total = total; } TimeSeries withTotal(long total) { return new TimeSeries(fiveMinutes, fifteenMinutes, twentyFourHours, total); } public static TimeSeries merge(TimeSeries first, TimeSeries second) { return new TimeSeries( first.fiveMinutes + second.fiveMinutes, first.fifteenMinutes + second.fifteenMinutes, first.twentyFourHours + second.twentyFourHours, first.total + second.total ); } public TimeSeries(StreamInput in) throws IOException { fiveMinutes = in.readVLong(); fifteenMinutes = in.readVLong(); twentyFourHours = in.readVLong(); if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) { total = in.readVLong(); } else { total = 0; } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { // total is omitted from toXContent as it's written at a higher level by ScriptContextStats builder.field(ScriptContextStats.Fields.FIVE_MINUTES, fiveMinutes); builder.field(ScriptContextStats.Fields.FIFTEEN_MINUTES, fifteenMinutes); builder.field(ScriptContextStats.Fields.TWENTY_FOUR_HOURS, twentyFourHours); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(fiveMinutes); out.writeVLong(fifteenMinutes); out.writeVLong(twentyFourHours); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) { out.writeVLong(total); } } public boolean areTimingsEmpty() { return fiveMinutes == 0 && fifteenMinutes == 0 && twentyFourHours == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TimeSeries that = (TimeSeries) o; return fiveMinutes == that.fiveMinutes && fifteenMinutes == that.fifteenMinutes && twentyFourHours == that.twentyFourHours && total == that.total; } @Override public int hashCode() { return Objects.hash(fiveMinutes, fifteenMinutes, twentyFourHours, total); } @Override public String toString() { return "TimeSeries{" + "fiveMinutes=" + fiveMinutes + ", fifteenMinutes=" + fifteenMinutes + ", twentyFourHours=" + twentyFourHours + ", total=" + total + '}'; } }
TimeSeries
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/PropertyRepo.java
{ "start": 417, "end": 580 }
class ____ { @Id private Long id; @ManyToAny @AnyDiscriminator(DiscriminatorType.STRING) private List<Property<?>> properties = new ArrayList<>(); }
PropertyRepo
java
grpc__grpc-java
binder/src/androidTest/java/io/grpc/binder/HostServices.java
{ "start": 3797, "end": 6508 }
class ____ (since Android itself is in control of the * services). */ public static void awaitServiceShutdown() throws InterruptedException { CountDownLatch latch = null; synchronized (HostServices.class) { if (serviceShutdownLatch == null && !activeServices.isEmpty()) { latch = new CountDownLatch(activeServices.size()); serviceShutdownLatch = latch; } serviceParams.clear(); serviceAddresses.clear(); } if (latch != null) { if (!latch.await(10, SECONDS)) { throw new AssertionError("Failed to shut down services"); } } synchronized (HostServices.class) { checkState(activeServices.isEmpty()); checkState(serviceParams.isEmpty()); checkState(serviceAddresses.isEmpty()); serviceShutdownLatch = null; } } /** Create the address for a host-service. */ private static AndroidComponentAddress hostServiceAddress(Context appContext, Class<?> cls) { // NOTE: Even though we have a context object, we intentionally don't use a "local", // address, since doing so would mark the address with our UID for security purposes, // and that would limit the effectiveness of tests. // Using this API forces us to rely on Binder.getCallingUid. return AndroidComponentAddress.forRemoteComponent(appContext.getPackageName(), cls.getName()); } /** * Allocate a new host service. * * @param appContext The application context. * @return The AndroidComponentAddress of the service. */ public static synchronized AndroidComponentAddress allocateService(Context appContext) { for (Class<?> cls : hostServiceClasses) { if (!serviceAddresses.containsKey(cls)) { AndroidComponentAddress address = hostServiceAddress(appContext, cls); serviceAddresses.put(cls, address); return address; } } throw new AssertionError("This test helper only supports two services at a time."); } /** * Configure an allocated hosting service. * * @param androidComponentAddress The address of the service. * @param params The parameters used to build the service. */ public static synchronized void configureService( AndroidComponentAddress androidComponentAddress, ServiceParams params) { for (Class<?> cls : hostServiceClasses) { if (serviceAddresses.get(cls).equals(androidComponentAddress)) { checkState(!serviceParams.containsKey(cls)); serviceParams.put(cls, params); return; } } throw new AssertionError("Unable to find service for address " + androidComponentAddress); } /** An Android Service to host each gRPC server. */ private abstract static
again
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/jackson/Log4jXmlModule.java
{ "start": 1161, "end": 1962 }
class ____ extends JacksonXmlModule { private static final long serialVersionUID = 1L; private final boolean includeStacktrace; private final boolean stacktraceAsString; Log4jXmlModule(final boolean includeStacktrace, final boolean stacktraceAsString) { this.includeStacktrace = includeStacktrace; this.stacktraceAsString = stacktraceAsString; // MUST init here. // Calling this from setupModule is too late! new SimpleModuleInitializer().initialize(this, false); } @Override public void setupModule(final SetupContext context) { // Calling super is a MUST! super.setupModule(context); new SetupContextAsEntryListInitializer().setupModule(context, includeStacktrace, stacktraceAsString); } }
Log4jXmlModule
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/ClassFilter.java
{ "start": 950, "end": 1600 }
interface ____ * provide proper implementations of {@link Object#equals(Object)}, * {@link Object#hashCode()}, and {@link Object#toString()} in order to allow the * filter to be used in caching scenarios &mdash; for example, in proxies generated * by CGLIB. As of Spring Framework 6.0.13, the {@code toString()} implementation * must generate a unique string representation that aligns with the logic used * to implement {@code equals()}. See concrete implementations of this interface * within the framework for examples. * * @author Rod Johnson * @author Sam Brannen * @see Pointcut * @see MethodMatcher */ @FunctionalInterface public
must
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/ClassNamePatternConverter.java
{ "start": 1532, "end": 2009 }
class ____", options); } /** * Gets an instance of ClassNamePatternConverter. * * @param options options, may be null. * @return instance of pattern converter. */ public static ClassNamePatternConverter newInstance(final String[] options) { return new ClassNamePatternConverter(options); } /** * Format a logging event. * * @param event event to format. * @param toAppendTo string buffer to which
name
java
quarkusio__quarkus
extensions/hibernate-search-orm-elasticsearch/deployment/src/test/java/io/quarkus/hibernate/search/orm/elasticsearch/test/devui/DevUIActiveFalseTest.java
{ "start": 177, "end": 688 }
class ____ extends AbstractDevUITest { @RegisterExtension static final QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot( (jar) -> jar.addAsResource("application-devui-active-false.properties", "application.properties") .addClasses(MyIndexedEntity.class)); public DevUIActiveFalseTest() { // Hibernate Search is inactive: the dev console should be empty. super(null, null); } }
DevUIActiveFalseTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableThrottleLatest.java
{ "start": 1496, "end": 2366 }
class ____<T> extends AbstractObservableWithUpstream<T, T> { final long timeout; final TimeUnit unit; final Scheduler scheduler; final boolean emitLast; final Consumer<? super T> onDropped; public ObservableThrottleLatest(Observable<T> source, long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast, Consumer<? super T> onDropped) { super(source); this.timeout = timeout; this.unit = unit; this.scheduler = scheduler; this.emitLast = emitLast; this.onDropped = onDropped; } @Override protected void subscribeActual(Observer<? super T> observer) { source.subscribe(new ThrottleLatestObserver<>(observer, timeout, unit, scheduler.createWorker(), emitLast, onDropped)); } static final
ObservableThrottleLatest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/util/ExpandedIdsMatcher.java
{ "start": 1237, "end": 6999 }
class ____ { /** * Split {@code expression} into tokens separated by a ',' * * @param expression Expression containing zero or more ','s * @return Array of tokens */ public static String[] tokenizeExpression(String expression) { return Strings.tokenizeToStringArray(expression, ","); } private final List<IdMatcher> allMatchers; private final List<IdMatcher> requiredMatches; private final boolean onlyExact; /** * Generate the list of required matches from the expressions in {@code tokens} * and initialize. * * @param tokens List of expressions that may be wildcards or full Ids * @param allowNoMatchForWildcards If true then it is not required for wildcard * expressions to match an Id meaning they are * not returned in the list of required matches */ public ExpandedIdsMatcher(String[] tokens, boolean allowNoMatchForWildcards) { requiredMatches = new LinkedList<>(); List<IdMatcher> allMatchers = new ArrayList<>(); if (Strings.isAllOrWildcard(tokens)) { // if allowNoJobForWildcards == true then any number // of jobs with any id is ok. Therefore no matches // are required IdMatcher matcher = new WildcardMatcher("*"); this.allMatchers = Collections.singletonList(matcher); if (allowNoMatchForWildcards == false) { // require something, anything to match requiredMatches.add(matcher); } onlyExact = false; return; } boolean atLeastOneWildcard = false; if (allowNoMatchForWildcards) { // matches are not required for wildcards but // specific job Ids are for (String token : tokens) { if (Regex.isSimpleMatchPattern(token)) { allMatchers.add(new WildcardMatcher(token)); atLeastOneWildcard = true; } else { IdMatcher matcher = new EqualsIdMatcher(token); allMatchers.add(matcher); requiredMatches.add(matcher); } } } else { // Matches are required for wildcards for (String token : tokens) { if (Regex.isSimpleMatchPattern(token)) { IdMatcher matcher = new WildcardMatcher(token); allMatchers.add(matcher); requiredMatches.add(matcher); atLeastOneWildcard = true; } else { IdMatcher matcher = new EqualsIdMatcher(token); allMatchers.add(matcher); requiredMatches.add(matcher); } } } onlyExact = atLeastOneWildcard == false; this.allMatchers = Collections.unmodifiableList(allMatchers); } /** * Generate the list of required matches from the {@code expression} * and initialize. * * @param expression Expression that will be tokenized into a set of wildcards or full Ids * @param allowNoMatchForWildcards If true then it is not required for wildcard * expressions to match an Id meaning they are * not returned in the list of required matches */ public ExpandedIdsMatcher(String expression, boolean allowNoMatchForWildcards) { this(tokenizeExpression(expression), allowNoMatchForWildcards); } /** * Test whether an ID matches any of the expressions. * Unlike {@link #filterMatchedIds} this does not modify the state of * the matcher. * @param id ID to test. * @return Does the ID match one or more of the patterns in the expression? */ public boolean idMatches(String id) { return allMatchers.stream().anyMatch(idMatcher -> idMatcher.matches(id)); } /** * For each {@code requiredMatchers} check there is an element * present in {@code ids} that matches. Once a match is made the * matcher is removed from {@code requiredMatchers}. */ public void filterMatchedIds(Collection<String> ids) { for (String id : ids) { Iterator<IdMatcher> itr = requiredMatches.iterator(); if (itr.hasNext() == false) { break; } while (itr.hasNext()) { if (itr.next().matches(id)) { itr.remove(); } } } } public boolean hasUnmatchedIds() { return requiredMatches.isEmpty() == false; } public List<String> unmatchedIds() { return requiredMatches.stream().map(IdMatcher::getId).collect(Collectors.toList()); } public String unmatchedIdsString() { return requiredMatches.stream().map(IdMatcher::getId).collect(Collectors.joining(",")); } /** * Whether ids are based on exact matchers or at least one contains a wildcard. * * @return true if only exact matches, false if at least one id contains a wildcard */ public boolean isOnlyExact() { return onlyExact; } /** * A simple matcher with one purpose to test whether an id * matches a expression that may contain wildcards. * Use the {@link #idMatches(String)} function to * test if the given id is matched by any of the matchers. * * Unlike {@link ExpandedIdsMatcher} there is no * allowNoMatchForWildcards logic and the matchers * are not be removed once they have been matched. */ public static
ExpandedIdsMatcher
java
dropwizard__dropwizard
dropwizard-testing/src/main/java/io/dropwizard/testing/junit5/ResourceExtension.java
{ "start": 442, "end": 637 }
class ____ implements DropwizardExtension { /** * A {@link ResourceExtension} builder which enables configuration of a Jersey testing environment. */ public static
ResourceExtension
java
quarkusio__quarkus
extensions/panache/hibernate-orm-panache/runtime/src/main/java/io/quarkus/hibernate/orm/panache/runtime/AdditionalJpaOperations.java
{ "start": 985, "end": 1176 }
class ____ only needed by the Spring Data JPA module and would not be placed there if it weren't for a dev-mode classloader issue // see https://github.com/quarkusio/quarkus/issues/6214 public
is
java
google__dagger
javatests/dagger/internal/codegen/MembersInjectionValidationTest.java
{ "start": 16520, "end": 16635 }
class ____ {", " @Provides", " String theString() { return \"\"; }", "}"); }
TestModule
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/internal/CheckForExistingForeignKeyTest.java
{ "start": 2872, "end": 3546 }
class ____ implements ColumnReferenceMapping { private ColumnInformation referencingColumnMetadata; private ColumnInformation referencedColumnMetadata; public ColumnReferenceMappingImpl(ColumnInformation referencingColumnMetadata, ColumnInformation referencedColumnMetadata) { this.referencingColumnMetadata = referencingColumnMetadata; this.referencedColumnMetadata = referencedColumnMetadata; } @Override public ColumnInformation getReferencingColumnMetadata() { return referencingColumnMetadata; } @Override public ColumnInformation getReferencedColumnMetadata() { return referencedColumnMetadata; } } private
ColumnReferenceMappingImpl
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/test/http/HttpConfig.java
{ "start": 4254, "end": 5039 }
class ____ extends Http1xOr2Config { public static HttpConfig DEFAULT = new HttpConfig.Http1x(); private final int port; private final String host; public Http1x(String host, int port) { this.port = port; this.host = host; } protected Http1x() { this(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT); } @Override public int port() { return port; } @Override public String host() { return host; } @Override public HttpServerOptions createBaseServerOptions() { return new HttpServerOptions().setPort(port).setHost(host); } @Override public HttpClientOptions createBaseClientOptions() { return new HttpClientOptions().setDefaultPort(port).setDefaultHost(host); } }
Http1x
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/EmbeddableWithParentWithInheritance2Test.java
{ "start": 2944, "end": 3269 }
class ____ { SmellOf smellOf; String name; public SmellOf getSmellOf() { return smellOf; } public void setSmellOf(SmellOf smellOf) { this.smellOf = smellOf; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Embeddable public static
Smell
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/MustParameterizedTest1.java
{ "start": 784, "end": 1274 }
class ____ extends TestCase { private String sql = "select * from t where id = 3 + 5"; private WallConfig config = new WallConfig(); protected void setUp() throws Exception { config.setMustParameterized(true); } public void testMySql() throws Exception { assertFalse(WallUtils.isValidateMySql(sql, config)); } public void testORACLE() throws Exception { assertFalse(WallUtils.isValidateOracle(sql, config)); } }
MustParameterizedTest1
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/TempBarrier.java
{ "start": 5920, "end": 7258 }
class ____ extends Thread { private final MutableObjectIterator<T> input; private final TypeSerializer<T> serializer; private final SpillingBuffer buffer; private volatile boolean running = true; private TempWritingThread( MutableObjectIterator<T> input, TypeSerializer<T> serializer, SpillingBuffer buffer) { super("Temp writer"); setDaemon(true); this.input = input; this.serializer = serializer; this.buffer = buffer; } @Override public void run() { final MutableObjectIterator<T> input = this.input; final TypeSerializer<T> serializer = this.serializer; final SpillingBuffer buffer = this.buffer; try { T record = serializer.createInstance(); while (this.running && ((record = input.next(record)) != null)) { serializer.serialize(record, buffer); } TempBarrier.this.writingDone(); } catch (Throwable t) { TempBarrier.this.setException(t); } } public void shutdown() { this.running = false; this.interrupt(); } } }
TempWritingThread
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/security/FormBasicAuthHttpRootTestCase.java
{ "start": 5100, "end": 5574 }
class ____ { private static final List<FormAuthenticationEvent> syncEvents = new CopyOnWriteArrayList<>(); private static final List<FormAuthenticationEvent> asyncEvents = new CopyOnWriteArrayList<>(); void observe(@Observes FormAuthenticationEvent event) { syncEvents.add(event); } void observeAsync(@ObservesAsync FormAuthenticationEvent event) { asyncEvents.add(event); } } }
FormAuthEventObserver
java
apache__rocketmq
proxy/src/test/java/org/apache/rocketmq/proxy/grpc/v2/AbstractMessingActivityTest.java
{ "start": 1493, "end": 3711 }
class ____ extends AbstractMessingActivity { public MockMessingActivity(MessagingProcessor messagingProcessor, GrpcClientSettingsManager grpcClientSettingsManager, GrpcChannelManager grpcChannelManager) { super(messagingProcessor, grpcClientSettingsManager, grpcChannelManager); } } private AbstractMessingActivity messingActivity; @Before public void before() throws Throwable { super.before(); this.messingActivity = new MockMessingActivity(null, null, null); } @Test public void testValidateTopic() { assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().setName(TopicValidator.RMQ_SYS_TRACE_TOPIC).build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().setName("@").build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().setName(createString(128)).build())); messingActivity.validateTopic(Resource.newBuilder().setName(createString(127)).build()); } @Test public void testValidateConsumer() { assertThrows(GrpcProxyException.class, () -> messingActivity.validateConsumerGroup(Resource.newBuilder().build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateConsumerGroup(Resource.newBuilder().setName(MixAll.CID_SYS_RMQ_TRANS).build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateConsumerGroup(Resource.newBuilder().setName("@").build())); assertThrows(GrpcProxyException.class, () -> messingActivity.validateConsumerGroup(Resource.newBuilder().setName(createString(256)).build())); messingActivity.validateConsumerGroup(Resource.newBuilder().setName(createString(120)).build()); } private static String createString(int len) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append('a'); } return sb.toString(); } }
MockMessingActivity
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytoone/foreignkey/RootLayer.java
{ "start": 538, "end": 1022 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "rootLayer", cascade = CascadeType.ALL, orphanRemoval = true) private List<MiddleLayer> middleLayers; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<MiddleLayer> getMiddleLayers() { return middleLayers; } public void setMiddleLayers(List<MiddleLayer> middleLayers) { this.middleLayers = middleLayers; } }
RootLayer
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest20.java
{ "start": 837, "end": 1094 }
class ____ extends TestCase { public void test_true() throws Exception { assertTrue(WallUtils.isValidateMySql(// "SET sql_mode=?,NAMES ?,CHARACTER SET utf8,CHARACTER_SET_RESULTS=utf8,COLLATION_CONNECTION=?")); } }
MySqlWallTest20
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/ClassLevelComputedPermissionsAllowedTest.java
{ "start": 3163, "end": 4416 }
class ____ have multiple params and Permission constructor selects one of them assertSuccess(() -> explicitlyMatchedParamsBean.autodetect("hello", "world", "!"), SUCCESS, user); assertFailureFor(() -> explicitlyMatchedParamsBean.autodetect("what", "ever", "?"), ForbiddenException.class, user); assertSuccess(explicitlyMatchedParamsBean.autodetectNonBlocking("hello", "world", "!"), SUCCESS, user); assertFailureFor(explicitlyMatchedParamsBean.autodetectNonBlocking("what", "ever", "?"), ForbiddenException.class, user); // differs from above in params number, which means number of different methods can be secured via class-level annotation assertSuccess(() -> explicitlyMatchedParamsBean.autodetect("world"), SUCCESS, user); assertFailureFor(() -> explicitlyMatchedParamsBean.autodetect("ever"), ForbiddenException.class, user); assertSuccess(explicitlyMatchedParamsBean.autodetectNonBlocking("world"), SUCCESS, user); assertFailureFor(explicitlyMatchedParamsBean.autodetectNonBlocking("ever"), ForbiddenException.class, user); } @PermissionsAllowed(value = IGNORED, permission = AllStrAutodetectedPermission.class) @Singleton public static
methods
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/OutputCommitter.java
{ "start": 10800, "end": 11187 }
interface ____ calling the old method. Note * that the input types are different between the new and old apis and this * is a bridge between the two. */ @Override public final void commitJob(org.apache.hadoop.mapreduce.JobContext context ) throws IOException { commitJob((JobContext) context); } /** * This method implements the new
by
java
apache__camel
components/camel-google/camel-google-drive/src/generated/java/org/apache/camel/component/google/drive/DriveFilesEndpointConfiguration.java
{ "start": 3713, "end": 23761 }
class ____ extends GoogleDriveConfiguration { @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "get", description="Whether the user is acknowledging the risk of downloading known malware or other abusive files"), @ApiMethod(methodName = "watch", description="Whether the user is acknowledging the risk of downloading known malware or other abusive files")}) private java.lang.Boolean acknowledgeAbuse; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "update", description="A comma-separated list of parent IDs to add")}) private java.lang.String addParents; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "watch", description="The com.google.api.services.drive.model.Channel")}) private com.google.api.services.drive.model.Channel channel; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "create", description="The com.google.api.services.drive.model.File media metadata or null if none")}) private com.google.api.services.drive.model.File content; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Bodies of items (files or documents) to which the query applies")}) private java.lang.String corpora; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Deprecated: The source of files to list")}) @Deprecated private java.lang.String corpus; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "generateIds", description="The number of IDs to return")}) private java.lang.Integer count; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "emptyTrash", description="If set, empties the trash of the provided shared drive"), @ApiMethod(methodName = "list", description="ID of the shared drive to search")}) private java.lang.String driveId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Deprecated: Copying files into multiple folders is no longer supported"), @ApiMethod(methodName = "create", description="Deprecated: Creating files in multiple folders is no longer supported"), @ApiMethod(methodName = "delete", description="Deprecated: If an item isn't in a shared drive and its last parent is deleted but the item itself isn't, the item will be placed under its owner's root"), @ApiMethod(methodName = "emptyTrash", description="Deprecated: If an item isn't in a shared drive and its last parent is deleted but the item itself isn't, the item will be placed under its owner's root"), @ApiMethod(methodName = "update", description="Deprecated: Adding files to multiple folders is no longer supported")}) @Deprecated private java.lang.Boolean enforceSingleParent; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "copy", description="The com.google.api.services.drive.model.File"), @ApiMethod(methodName = "update", description="The com.google.api.services.drive.model.File media metadata or null if none")}) private com.google.api.services.drive.model.File file; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "copy", description="The ID of the file"), @ApiMethod(methodName = "delete", description="The ID of the file"), @ApiMethod(methodName = "download", description="Required. The ID of the file to download."), @ApiMethod(methodName = "export", description="The ID of the file"), @ApiMethod(methodName = "get", description="The ID of the file"), @ApiMethod(methodName = "listLabels", description="The ID for the file"), @ApiMethod(methodName = "modifyLabels", description="The ID of the file to which the labels belong"), @ApiMethod(methodName = "update", description="The ID of the file"), @ApiMethod(methodName = "watch", description="The ID of the file")}) private String fileId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Whether to ignore the domain's default visibility settings for the created file"), @ApiMethod(methodName = "create", description="Whether to ignore the domain's default visibility settings for the created file")}) private java.lang.Boolean ignoreDefaultVisibility; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Whether both My Drive and shared drive items should be included in results")}) private java.lang.Boolean includeItemsFromAllDrives; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response"), @ApiMethod(methodName = "create", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response"), @ApiMethod(methodName = "get", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response"), @ApiMethod(methodName = "list", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response"), @ApiMethod(methodName = "update", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response"), @ApiMethod(methodName = "watch", description="A comma-separated list of IDs of labels to include in the labelInfo part of the response")}) private java.lang.String includeLabels; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Specifies which additional view's permissions to include in the response"), @ApiMethod(methodName = "create", description="Specifies which additional view's permissions to include in the response"), @ApiMethod(methodName = "get", description="Specifies which additional view's permissions to include in the response"), @ApiMethod(methodName = "list", description="Specifies which additional view's permissions to include in the response"), @ApiMethod(methodName = "update", description="Specifies which additional view's permissions to include in the response"), @ApiMethod(methodName = "watch", description="Specifies which additional view's permissions to include in the response")}) private java.lang.String includePermissionsForView; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Deprecated: Use includeItemsFromAllDrives instead")}) @Deprecated private java.lang.Boolean includeTeamDriveItems; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Whether to set the keepForever field in the new head revision"), @ApiMethod(methodName = "create", description="Whether to set the keepForever field in the new head revision"), @ApiMethod(methodName = "update", description="Whether to set the keepForever field in the new head revision")}) private java.lang.Boolean keepRevisionForever; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "listLabels", description="The maximum number of labels to return per page")}) private java.lang.Integer maxResults; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "create", description="The media HTTP content"), @ApiMethod(methodName = "update", description="The media HTTP content")}) private com.google.api.client.http.AbstractInputStreamContent mediaContent; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "download", description="Optional"), @ApiMethod(methodName = "export", description="Required. The MIME type of the format requested for this export. For a list of supported MIME types, see Export MIME types for Google Workspace documents(/workspace/drive/api/guides/ref- export-formats).")}) private java.lang.String mimeType; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "modifyLabels", description="The com.google.api.services.drive.model.ModifyLabelsRequest")}) private com.google.api.services.drive.model.ModifyLabelsRequest modifyLabelsRequest; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="A language hint for OCR processing during image import (ISO 639-1 code)"), @ApiMethod(methodName = "create", description="A language hint for OCR processing during image import (ISO 639-1 code)"), @ApiMethod(methodName = "update", description="A language hint for OCR processing during image import (ISO 639-1 code)")}) private java.lang.String ocrLanguage; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="A comma-separated list of sort keys")}) private java.lang.String orderBy; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="The maximum number of files to return per page")}) private java.lang.Integer pageSize; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="The token for continuing a previous list request on the next page"), @ApiMethod(methodName = "listLabels", description="The token for continuing a previous list request on the next page")}) private java.lang.String pageToken; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="A query for filtering the file results")}) private java.lang.String q; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "update", description="A comma-separated list of parent IDs to remove")}) private java.lang.String removeParents; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "download", description="Optional")}) private java.lang.String revisionId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "generateIds", description="The space in which the IDs can be used to create files")}) private java.lang.String space; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="A comma-separated list of spaces to query within the corpora")}) private java.lang.String spaces; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "create", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "delete", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "get", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "list", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "update", description="Whether the requesting application supports both My Drives and shared drives"), @ApiMethod(methodName = "watch", description="Whether the requesting application supports both My Drives and shared drives")}) private java.lang.Boolean supportsAllDrives; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "copy", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "create", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "delete", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "get", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "list", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "update", description="Deprecated: Use supportsAllDrives instead"), @ApiMethod(methodName = "watch", description="Deprecated: Use supportsAllDrives instead")}) @Deprecated private java.lang.Boolean supportsTeamDrives; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Deprecated: Use driveId instead")}) @Deprecated private java.lang.String teamDriveId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "generateIds", description="The type of items which the IDs can be used for")}) private java.lang.String type; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "create", description="Whether to use the uploaded content as indexable text"), @ApiMethod(methodName = "update", description="Whether to use the uploaded content as indexable text")}) private java.lang.Boolean useContentAsIndexableText; public java.lang.Boolean getAcknowledgeAbuse() { return acknowledgeAbuse; } public void setAcknowledgeAbuse(java.lang.Boolean acknowledgeAbuse) { this.acknowledgeAbuse = acknowledgeAbuse; } public java.lang.String getAddParents() { return addParents; } public void setAddParents(java.lang.String addParents) { this.addParents = addParents; } public com.google.api.services.drive.model.Channel getChannel() { return channel; } public void setChannel(com.google.api.services.drive.model.Channel channel) { this.channel = channel; } public com.google.api.services.drive.model.File getContent() { return content; } public void setContent(com.google.api.services.drive.model.File content) { this.content = content; } public java.lang.String getCorpora() { return corpora; } public void setCorpora(java.lang.String corpora) { this.corpora = corpora; } public java.lang.String getCorpus() { return corpus; } public void setCorpus(java.lang.String corpus) { this.corpus = corpus; } public java.lang.Integer getCount() { return count; } public void setCount(java.lang.Integer count) { this.count = count; } public java.lang.String getDriveId() { return driveId; } public void setDriveId(java.lang.String driveId) { this.driveId = driveId; } public java.lang.Boolean getEnforceSingleParent() { return enforceSingleParent; } public void setEnforceSingleParent(java.lang.Boolean enforceSingleParent) { this.enforceSingleParent = enforceSingleParent; } public com.google.api.services.drive.model.File getFile() { return file; } public void setFile(com.google.api.services.drive.model.File file) { this.file = file; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public java.lang.Boolean getIgnoreDefaultVisibility() { return ignoreDefaultVisibility; } public void setIgnoreDefaultVisibility(java.lang.Boolean ignoreDefaultVisibility) { this.ignoreDefaultVisibility = ignoreDefaultVisibility; } public java.lang.Boolean getIncludeItemsFromAllDrives() { return includeItemsFromAllDrives; } public void setIncludeItemsFromAllDrives(java.lang.Boolean includeItemsFromAllDrives) { this.includeItemsFromAllDrives = includeItemsFromAllDrives; } public java.lang.String getIncludeLabels() { return includeLabels; } public void setIncludeLabels(java.lang.String includeLabels) { this.includeLabels = includeLabels; } public java.lang.String getIncludePermissionsForView() { return includePermissionsForView; } public void setIncludePermissionsForView(java.lang.String includePermissionsForView) { this.includePermissionsForView = includePermissionsForView; } public java.lang.Boolean getIncludeTeamDriveItems() { return includeTeamDriveItems; } public void setIncludeTeamDriveItems(java.lang.Boolean includeTeamDriveItems) { this.includeTeamDriveItems = includeTeamDriveItems; } public java.lang.Boolean getKeepRevisionForever() { return keepRevisionForever; } public void setKeepRevisionForever(java.lang.Boolean keepRevisionForever) { this.keepRevisionForever = keepRevisionForever; } public java.lang.Integer getMaxResults() { return maxResults; } public void setMaxResults(java.lang.Integer maxResults) { this.maxResults = maxResults; } public com.google.api.client.http.AbstractInputStreamContent getMediaContent() { return mediaContent; } public void setMediaContent(com.google.api.client.http.AbstractInputStreamContent mediaContent) { this.mediaContent = mediaContent; } public java.lang.String getMimeType() { return mimeType; } public void setMimeType(java.lang.String mimeType) { this.mimeType = mimeType; } public com.google.api.services.drive.model.ModifyLabelsRequest getModifyLabelsRequest() { return modifyLabelsRequest; } public void setModifyLabelsRequest(com.google.api.services.drive.model.ModifyLabelsRequest modifyLabelsRequest) { this.modifyLabelsRequest = modifyLabelsRequest; } public java.lang.String getOcrLanguage() { return ocrLanguage; } public void setOcrLanguage(java.lang.String ocrLanguage) { this.ocrLanguage = ocrLanguage; } public java.lang.String getOrderBy() { return orderBy; } public void setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; } public java.lang.Integer getPageSize() { return pageSize; } public void setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; } public java.lang.String getPageToken() { return pageToken; } public void setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; } public java.lang.String getQ() { return q; } public void setQ(java.lang.String q) { this.q = q; } public java.lang.String getRemoveParents() { return removeParents; } public void setRemoveParents(java.lang.String removeParents) { this.removeParents = removeParents; } public java.lang.String getRevisionId() { return revisionId; } public void setRevisionId(java.lang.String revisionId) { this.revisionId = revisionId; } public java.lang.String getSpace() { return space; } public void setSpace(java.lang.String space) { this.space = space; } public java.lang.String getSpaces() { return spaces; } public void setSpaces(java.lang.String spaces) { this.spaces = spaces; } public java.lang.Boolean getSupportsAllDrives() { return supportsAllDrives; } public void setSupportsAllDrives(java.lang.Boolean supportsAllDrives) { this.supportsAllDrives = supportsAllDrives; } public java.lang.Boolean getSupportsTeamDrives() { return supportsTeamDrives; } public void setSupportsTeamDrives(java.lang.Boolean supportsTeamDrives) { this.supportsTeamDrives = supportsTeamDrives; } public java.lang.String getTeamDriveId() { return teamDriveId; } public void setTeamDriveId(java.lang.String teamDriveId) { this.teamDriveId = teamDriveId; } public java.lang.String getType() { return type; } public void setType(java.lang.String type) { this.type = type; } public java.lang.Boolean getUseContentAsIndexableText() { return useContentAsIndexableText; } public void setUseContentAsIndexableText(java.lang.Boolean useContentAsIndexableText) { this.useContentAsIndexableText = useContentAsIndexableText; } }
DriveFilesEndpointConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/table/EmbeddedTableTests.java
{ "start": 8764, "end": 9081 }
class ____ { @Id private Integer id; private String name; @Embedded @AttributeOverride(name="text", column = @Column(table = "posts_compliant_secondary") ) @AttributeOverride(name="added", column = @Column(table = "posts_compliant_secondary") ) private Tag tag; } @Embeddable public static
PostCompliant
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/PointwisePatternTest.java
{ "start": 2142, "end": 11655 }
class ____ { @RegisterExtension static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE = TestingUtils.defaultExecutorExtension(); @Test void testNToN() throws Exception { final int N = 23; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(N, N); for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(1); assertThat(ev.getParallelSubtaskIndex()) .isEqualTo(consumedPartitionGroup.getFirst().getPartitionNumber()); } } @Test void test2NToN() throws Exception { final int N = 17; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(2 * N, N); for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(2); int idx = 0; for (IntermediateResultPartitionID partitionId : consumedPartitionGroup) { assertThat(ev.getParallelSubtaskIndex() * 2L + idx++) .isEqualTo(partitionId.getPartitionNumber()); } } } @Test void test3NToN() throws Exception { final int N = 17; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(3 * N, N); for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(3); int idx = 0; for (IntermediateResultPartitionID partitionId : consumedPartitionGroup) { assertThat(ev.getParallelSubtaskIndex() * 3L + idx++) .isEqualTo(partitionId.getPartitionNumber()); } } } @Test void testNTo2N() throws Exception { final int N = 41; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(N, 2 * N); for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(1); assertThat(ev.getParallelSubtaskIndex() / 2) .isEqualTo(consumedPartitionGroup.getFirst().getPartitionNumber()); } } @Test void testNTo7N() throws Exception { final int N = 11; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(N, 7 * N); for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(1); assertThat(ev.getParallelSubtaskIndex() / 7) .isEqualTo(consumedPartitionGroup.getFirst().getPartitionNumber()); } } @Test void testLowHighIrregular() throws Exception { testLowToHigh(3, 16); testLowToHigh(19, 21); testLowToHigh(15, 20); testLowToHigh(11, 31); testLowToHigh(11, 29); } @Test void testHighLowIrregular() throws Exception { testHighToLow(16, 3); testHighToLow(21, 19); testHighToLow(20, 15); testHighToLow(31, 11); } /** * Verify the connection sequences for POINTWISE edges is correct and make sure the descendant * logic of building POINTWISE edges follows the initial logic. */ @Test void testPointwiseConnectionSequence() throws Exception { // upstream parallelism < downstream parallelism testConnections(3, 5, new int[][] {{0}, {0}, {1}, {1}, {2}}); testConnections(3, 10, new int[][] {{0}, {0}, {0}, {0}, {1}, {1}, {1}, {2}, {2}, {2}}); testConnections(4, 6, new int[][] {{0}, {0}, {1}, {2}, {2}, {3}}); testConnections(6, 10, new int[][] {{0}, {0}, {1}, {1}, {2}, {3}, {3}, {4}, {4}, {5}}); // upstream parallelism > downstream parallelism testConnections(5, 3, new int[][] {{0}, {1, 2}, {3, 4}}); testConnections(10, 3, new int[][] {{0, 1, 2}, {3, 4, 5}, {6, 7, 8, 9}}); testConnections(6, 4, new int[][] {{0}, {1, 2}, {3}, {4, 5}}); testConnections(10, 6, new int[][] {{0}, {1, 2}, {3, 4}, {5}, {6, 7}, {8, 9}}); } private void testLowToHigh(int lowDop, int highDop) throws Exception { if (highDop < lowDop) { throw new IllegalArgumentException(); } final int factor = highDop / lowDop; final int delta = highDop % lowDop == 0 ? 0 : 1; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(lowDop, highDop); int[] timesUsed = new int[lowDop]; for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(consumedPartitionGroup).hasSize(1); timesUsed[consumedPartitionGroup.getFirst().getPartitionNumber()]++; } for (int used : timesUsed) { assertThat(used >= factor && used <= factor + delta).isTrue(); } } private void testHighToLow(int highDop, int lowDop) throws Exception { if (highDop < lowDop) { throw new IllegalArgumentException(); } final int factor = highDop / lowDop; final int delta = highDop % lowDop == 0 ? 0 : 1; ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(highDop, lowDop); int[] timesUsed = new int[highDop]; for (ExecutionVertex ev : target.getTaskVertices()) { assertThat(ev.getNumberOfInputs()).isOne(); List<IntermediateResultPartitionID> consumedPartitions = new ArrayList<>(); for (ConsumedPartitionGroup partitionGroup : ev.getAllConsumedPartitionGroups()) { for (IntermediateResultPartitionID partitionId : partitionGroup) { consumedPartitions.add(partitionId); } } assertThat( consumedPartitions.size() >= factor && consumedPartitions.size() <= factor + delta) .isTrue(); for (IntermediateResultPartitionID consumedPartition : consumedPartitions) { timesUsed[consumedPartition.getPartitionNumber()]++; } } for (int used : timesUsed) { assertThat(used).isOne(); } } private ExecutionJobVertex setUpExecutionGraphAndGetDownstreamVertex( int upstream, int downstream) throws Exception { JobVertex v1 = new JobVertex("vertex1"); JobVertex v2 = new JobVertex("vertex2"); v1.setParallelism(upstream); v2.setParallelism(downstream); v1.setInvokableClass(AbstractInvokable.class); v2.setInvokableClass(AbstractInvokable.class); connectNewDataSetAsInput( v2, v1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED); List<JobVertex> ordered = new ArrayList<>(Arrays.asList(v1, v2)); ExecutionGraph eg = TestingDefaultExecutionGraphBuilder.newBuilder() .setVertexParallelismStore( SchedulerBase.computeVertexParallelismStore(ordered)) .build(EXECUTOR_RESOURCE.getExecutor()); try { eg.attachJobGraph( ordered, UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup()); } catch (JobException e) { e.printStackTrace(); fail("Job failed with exception: " + e.getMessage()); } return eg.getAllVertices().get(v2.getID()); } /** Verify the connections between upstream result partitions and downstream vertices. */ private void testConnections( int sourceParallelism, int targetParallelism, int[][] expectedConsumedPartitionNumber) throws Exception { ExecutionJobVertex target = setUpExecutionGraphAndGetDownstreamVertex(sourceParallelism, targetParallelism); for (int vertexIndex = 0; vertexIndex < target.getTaskVertices().length; vertexIndex++) { ExecutionVertex ev = target.getTaskVertices()[vertexIndex]; ConsumedPartitionGroup consumedPartitionGroup = ev.getConsumedPartitionGroup(0); assertThat(expectedConsumedPartitionNumber[vertexIndex].length) .isEqualTo(consumedPartitionGroup.size()); int partitionIndex = 0; for (IntermediateResultPartitionID partitionId : consumedPartitionGroup) { assertThat(expectedConsumedPartitionNumber[vertexIndex][partitionIndex++]) .isEqualTo(partitionId.getPartitionNumber()); } } } }
PointwisePatternTest
java
playframework__playframework
core/play/src/main/java/play/inject/BindingKey.java
{ "start": 3632, "end": 4706 }
class ____ be instantiated and injected by the injection framework. */ public Binding<T> to(final Class<? extends T> implementation) { return underlying.to(implementation).asJava(); } /** * Bind this binding key to the given provider instance. * * <p>This provider instance will be invoked to obtain the implementation for the key. */ public Binding<T> to(final Provider<? extends T> provider) { return underlying.to(provider).asJava(); } /** Bind this binding key to the given instance. */ public <A extends T> Binding<T> to(final Supplier<A> instance) { return underlying.to(FunctionConverters.asScalaFromSupplier(instance)).asJava(); } /** Bind this binding key to another binding key. */ public Binding<T> to(final BindingKey<? extends T> key) { return underlying.to(key.asScala()).asJava(); } /** * Bind this binding key to the given provider class. * * <p>The dependency injection framework will instantiate and inject this provider, and then * invoke its `get` method whenever an instance of the
will
java
quarkusio__quarkus
integration-tests/opentelemetry-reactive-messaging/src/main/java/io/quarkus/it/opentelemetry/TracedKafkaConsumer.java
{ "start": 316, "end": 540 }
class ____ { @Inject TracedService tracedService; @Incoming("traces-in") CompletionStage<Void> consume(Message<String> msg) { tracedService.call(); return msg.ack(); } }
TracedKafkaConsumer
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/LogCaptureTest.java
{ "start": 1179, "end": 1441 }
class ____ { @Test public void testCapture() { InternalLoggerFactory.getInstance(ResourceLeakDetector.class).error("testError"); assertFalse(LogCaptureAppender.getEvents().isEmpty()); LogCaptureAppender.reset(); } }
LogCaptureTest
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/module/ManifestParserTest.java
{ "start": 4772, "end": 5219 }
class ____ implements GlideModule { @Override public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {} @Override public void registerComponents(Context context, Glide glide, Registry registry) {} @Override public boolean equals(Object o) { return o instanceof TestModule1; } @Override public int hashCode() { return super.hashCode(); } } public static
TestModule1
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyConverterTest.java
{ "start": 1292, "end": 2211 }
class ____ extends CamelTestSupport { /** * Test payload to send. */ private static final String PAYLOAD = "Test Message"; private ByteBuf buf; @BeforeEach public void startUp() { byte[] bytes = PAYLOAD.getBytes(); buf = PooledByteBufAllocator.DEFAULT.buffer(bytes.length); buf.writeBytes(bytes); } @Override public void doPostTearDown() { buf.release(); } @Test public void testConversionWithExchange() { String result = context.getTypeConverter().convertTo(String.class, new DefaultExchange(context), buf); assertNotNull(result); assertEquals(PAYLOAD, result); } @Test public void testConversionWithoutExchange() { String result = context.getTypeConverter().convertTo(String.class, buf); assertNotNull(result); assertEquals(PAYLOAD, result); } }
NettyConverterTest
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/annotation/UniqueSecurityAnnotationScannerTests.java
{ "start": 15250, "end": 15537 }
interface ____ { void add(@CustomParameterAnnotation("one") String user); List<String> list(@CustomParameterAnnotation("two") String user); String get(@CustomParameterAnnotation("three") String user); void delete(@CustomParameterAnnotation("five") String user); }
UserService
java
apache__kafka
connect/transforms/src/test/java/org/apache/kafka/connect/transforms/field/FieldSyntaxVersionTest.java
{ "start": 1382, "end": 3268 }
class ____ { @Test void shouldAppendConfigToDef() { ConfigDef def = FieldSyntaxVersion.appendConfigTo(new ConfigDef()); assertEquals(1, def.configKeys().size()); final ConfigDef.ConfigKey configKey = def.configKeys().get("field.syntax.version"); assertEquals("field.syntax.version", configKey.name); assertEquals("V1", configKey.defaultValue); } @Test void shouldFailWhenAppendConfigToDefAgain() { ConfigDef def = FieldSyntaxVersion.appendConfigTo(new ConfigDef()); assertEquals(1, def.configKeys().size()); ConfigException e = assertThrows(ConfigException.class, () -> FieldSyntaxVersion.appendConfigTo(def)); assertEquals("Configuration field.syntax.version is defined twice.", e.getMessage()); } @ParameterizedTest @CsvSource({"v1,V1", "v2,V2", "V1,V1", "V2,V2"}) void shouldGetVersionFromConfig(String input, FieldSyntaxVersion version) { Map<String, String> configs = new HashMap<>(); configs.put("field.syntax.version", input); AbstractConfig config = new AbstractConfig(FieldSyntaxVersion.appendConfigTo(new ConfigDef()), configs); assertEquals(version, FieldSyntaxVersion.fromConfig(config)); } @ParameterizedTest @ValueSource(strings = {"v3", "V 1", "v", "V 2", "2", "1"}) void shouldFailWhenWrongVersionIsPassed(String input) { Map<String, String> configs = new HashMap<>(); configs.put("field.syntax.version", input); ConfigException e = assertThrows(ConfigException.class, () -> new AbstractConfig(FieldSyntaxVersion.appendConfigTo(new ConfigDef()), configs)); assertEquals( "Invalid value " + input + " for configuration field.syntax.version: " + "String must be one of (case insensitive): V1, V2", e.getMessage()); } }
FieldSyntaxVersionTest
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageSendingOperations.java
{ "start": 1876, "end": 3666 }
interface ____ extends MessageSendingOperations<String> { /** * Send a message to the given user. * @param user the user that should receive the message. * @param destination the destination to send the message to. * @param payload the payload to send */ void convertAndSendToUser(String user, String destination, Object payload) throws MessagingException; /** * Send a message to the given user. * <p>By default headers are interpreted as native headers (for example, STOMP) and * are saved under a special key in the resulting Spring * {@link org.springframework.messaging.Message Message}. In effect when the * message leaves the application, the provided headers are included with it * and delivered to the destination (for example, the STOMP client or broker). * <p>If the map already contains the key * {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS "nativeHeaders"} * or was prepared with * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor SimpMessageHeaderAccessor} * then the headers are used directly. A common expected case is providing a * content type (to influence the message conversion) and native headers. * This may be done as follows: * <pre class="code"> * SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); * accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); * accessor.setNativeHeader("foo", "bar"); * accessor.setLeaveMutable(true); * MessageHeaders headers = accessor.getMessageHeaders(); * messagingTemplate.convertAndSendToUser(user, destination, payload, headers); * </pre> * <p><strong>Note:</strong> if the {@code MessageHeaders} are mutable as in * the above example, implementations of this
SimpMessageSendingOperations
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/com/github/xds/service/orca/v3/OpenRcaServiceGrpc.java
{ "start": 6251, "end": 6625 }
interface ____ { /** */ default void streamCoreMetrics(com.github.xds.service.orca.v3.OrcaLoadReportRequest request, io.grpc.stub.StreamObserver<com.github.xds.data.orca.v3.OrcaLoadReport> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getStreamCoreMetricsMethod(), responseObserver); } } /** * Base
AsyncService
java
square__retrofit
retrofit/java-test/src/test/java/retrofit2/RetrofitTest.java
{ "start": 49214, "end": 50518 }
class ____.lang.String.\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingCallAdapterFactory\n" + " * retrofit2.CompletableFutureCallAdapterFactory\n" + " * retrofit2.DefaultCallAdapterFactory"); } assertThat(nonMatchingFactory.called).isTrue(); } @Test public void callAdapterFactoryDelegateNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; DelegatingCallAdapterFactory delegatingFactory1 = new DelegatingCallAdapterFactory(); DelegatingCallAdapterFactory delegatingFactory2 = new DelegatingCallAdapterFactory(); NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://example.com/") .addCallAdapterFactory(delegatingFactory1) .addCallAdapterFactory(delegatingFactory2) .addCallAdapterFactory(nonMatchingFactory) .build(); try { retrofit.callAdapter(type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageThat() .isEqualTo( "" + "Could not locate call adapter for
java
java
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/core/DefaultLauncherSession.java
{ "start": 1293, "end": 3045 }
class ____ implements LauncherSession { private static final LauncherInterceptor NOOP_INTERCEPTOR = new LauncherInterceptor() { @Override public <T> T intercept(Invocation<T> invocation) { return invocation.proceed(); } @Override public void close() { // do nothing } }; private final NamespacedHierarchicalStore<Namespace> store = new NamespacedHierarchicalStore<>(null, closeAutoCloseables()); private final LauncherInterceptor interceptor; private final LauncherSessionListener listener; private final DelegatingLauncher launcher; DefaultLauncherSession(List<LauncherInterceptor> interceptors, // Supplier<LauncherSessionListener> listenerSupplier, // Function<NamespacedHierarchicalStore<Namespace>, Launcher> launcherFactory // ) { interceptor = composite(interceptors); Launcher launcher; if (interceptor == NOOP_INTERCEPTOR) { this.listener = listenerSupplier.get(); launcher = launcherFactory.apply(this.store); } else { this.listener = interceptor.intercept(listenerSupplier::get); launcher = new InterceptingLauncher(interceptor.intercept(() -> launcherFactory.apply(this.store)), interceptor); } this.launcher = new DelegatingLauncher(launcher); listener.launcherSessionOpened(this); } @Override public Launcher getLauncher() { return launcher; } LauncherSessionListener getListener() { return listener; } @Override public void close() { if (launcher.delegate != ClosedLauncher.INSTANCE) { launcher.delegate = ClosedLauncher.INSTANCE; listener.launcherSessionClosed(this); store.close(); interceptor.close(); } } @Override public NamespacedHierarchicalStore<Namespace> getStore() { return store; } private static
DefaultLauncherSession
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/UnRegisterNodeManagerRequest.java
{ "start": 1025, "end": 1428 }
class ____ { public static UnRegisterNodeManagerRequest newInstance(NodeId nodeId) { UnRegisterNodeManagerRequest nodeHeartbeatRequest = Records .newRecord(UnRegisterNodeManagerRequest.class); nodeHeartbeatRequest.setNodeId(nodeId); return nodeHeartbeatRequest; } public abstract NodeId getNodeId(); public abstract void setNodeId(NodeId nodeId); }
UnRegisterNodeManagerRequest
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/BeforeAll.java
{ "start": 2348, "end": 2453 }
interface ____ inherited * as long as they are not overridden, and {@code @BeforeAll} methods from an *
are
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/SimpleTimerService.java
{ "start": 1122, "end": 2281 }
class ____ implements TimerService { private final InternalTimerService<VoidNamespace> internalTimerService; public SimpleTimerService(InternalTimerService<VoidNamespace> internalTimerService) { this.internalTimerService = internalTimerService; } @Override public long currentProcessingTime() { return internalTimerService.currentProcessingTime(); } @Override public long currentWatermark() { return internalTimerService.currentWatermark(); } @Override public void registerProcessingTimeTimer(long time) { internalTimerService.registerProcessingTimeTimer(VoidNamespace.INSTANCE, time); } @Override public void registerEventTimeTimer(long time) { internalTimerService.registerEventTimeTimer(VoidNamespace.INSTANCE, time); } @Override public void deleteProcessingTimeTimer(long time) { internalTimerService.deleteProcessingTimeTimer(VoidNamespace.INSTANCE, time); } @Override public void deleteEventTimeTimer(long time) { internalTimerService.deleteEventTimeTimer(VoidNamespace.INSTANCE, time); } }
SimpleTimerService
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopIntFloatAggregator.java
{ "start": 3136, "end": 4370 }
class ____ implements GroupingAggregatorState { private final IntFloatBucketedSort sort; private GroupingState(BigArrays bigArrays, int limit, boolean ascending) { this.sort = new IntFloatBucketedSort(bigArrays, ascending ? SortOrder.ASC : SortOrder.DESC, limit); } public void add(int groupId, int value, float outputValue) { sort.collect(value, outputValue, groupId); } @Override public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) { sort.toBlocks(driverContext.blockFactory(), blocks, offset, selected); } Block toBlock(BlockFactory blockFactory, IntVector selected) { Block[] blocks = new Block[2]; sort.toBlocks(blockFactory, blocks, 0, selected); Releasables.close(blocks[0]); return blocks[1]; } @Override public void enableGroupIdTracking(SeenGroupIds seen) { // we figure out seen values from nulls on the values block } @Override public void close() { Releasables.closeExpectNoException(sort); } } public static
GroupingState
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java
{ "start": 1715, "end": 6613 }
class ____ { private final ResourceHttpMessageConverter converter = new ResourceHttpMessageConverter(); @Test void canReadResource() { assertThat(converter.canRead(Resource.class, new MediaType("application", "octet-stream"))).isTrue(); } @Test void canWriteResource() { assertThat(converter.canWrite(Resource.class, new MediaType("application", "octet-stream"))).isTrue(); assertThat(converter.canWrite(Resource.class, MediaType.ALL)).isTrue(); } @Test void shouldReadImageResource() throws IOException { byte[] body = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("logo.jpg")); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG); inputMessage.getHeaders().setContentDisposition( ContentDisposition.attachment().filename("yourlogo.jpg").build()); Resource actualResource = converter.read(Resource.class, inputMessage); assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream())).isEqualTo(body); assertThat(actualResource.getFilename()).isEqualTo("yourlogo.jpg"); } @Test // SPR-13443 public void shouldReadInputStreamResource() throws IOException { try (InputStream body = getClass().getResourceAsStream("logo.jpg") ) { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG); inputMessage.getHeaders().setContentDisposition( ContentDisposition.attachment().filename("yourlogo.jpg").build()); inputMessage.getHeaders().setContentLength(123); Resource actualResource = converter.read(InputStreamResource.class, inputMessage); assertThat(actualResource).isInstanceOf(InputStreamResource.class); assertThat(actualResource.getInputStream()).isEqualTo(body); assertThat(actualResource.getFilename()).isEqualTo("yourlogo.jpg"); assertThat(actualResource.contentLength()).isEqualTo(123); } } @Test // SPR-14882 public void shouldNotReadInputStreamResource() throws IOException { ResourceHttpMessageConverter noStreamConverter = new ResourceHttpMessageConverter(false); try (InputStream body = getClass().getResourceAsStream("logo.jpg") ) { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG); assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> noStreamConverter.read(InputStreamResource.class, inputMessage)); } } @Test void shouldWriteImageResource() throws IOException { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource body = new ClassPathResource("logo.jpg", getClass()); converter.write(body, null, outputMessage); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(MediaType.IMAGE_JPEG); assertThat(outputMessage.getHeaders().getContentLength()) .as("Invalid content-length").isEqualTo(body.getFile().length()); } @Test // SPR-10848 public void writeByteArrayNullMediaType() throws IOException { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); byte[] byteArray = {1, 2, 3}; Resource body = new ByteArrayResource(byteArray); converter.write(body, null, outputMessage); assertThat(Arrays.equals(byteArray, outputMessage.getBodyAsBytes())).isTrue(); } @Test // SPR-12999 public void writeContentNotGettingInputStream() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource resource = mock(); given(resource.getInputStream()).willThrow(FileNotFoundException.class); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } @Test // SPR-12999 public void writeContentNotClosingInputStream() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource resource = mock(); InputStream inputStream = mock(); given(resource.getInputStream()).willReturn(inputStream); given(inputStream.read(any())).willReturn(-1); willThrow(new NullPointerException()).given(inputStream).close(); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } @Test // SPR-13620 public void writeContentInputStreamThrowingNullPointerException() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource resource = mock(); InputStream in = mock(); given(resource.getInputStream()).willReturn(in); given(in.read(any())).willThrow(NullPointerException.class); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } }
ResourceHttpMessageConverterTests
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegationV2.java
{ "start": 2040, "end": 4830 }
class ____ extends MetadataServiceV2ImplBase { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final FrameworkModel frameworkModel; private final RegistryManager registryManager; private URL metadataUrl; public static final String VERSION = "2.0.0"; public MetadataServiceDelegationV2(ApplicationModel applicationModel) { frameworkModel = applicationModel.getFrameworkModel(); registryManager = RegistryManager.getInstance(applicationModel); } @Override public org.apache.dubbo.metadata.MetadataInfoV2 getMetadataInfo(MetadataRequest metadataRequestV2) { String revision = metadataRequestV2.getRevision(); MetadataInfo info; if (StringUtils.isEmpty(revision)) { return null; } for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) { info = sd.getLocalMetadata(revision); if (info != null && revision.equals(info.getRevision())) { return toV2(info); } } if (logger.isWarnEnabled()) { logger.warn( REGISTRY_FAILED_LOAD_METADATA, "", "", "metadataV2 not found for revision: " + metadataRequestV2); } return null; } @Override public OpenAPIInfo getOpenAPIInfo(org.apache.dubbo.metadata.OpenAPIRequest request) { if (TripleProtocol.OPENAPI_ENABLED) { OpenAPIService openAPIService = frameworkModel.getBean(OpenAPIService.class); if (openAPIService != null) { OpenAPIRequest oRequest = new OpenAPIRequest(); oRequest.setGroup(request.getGroup()); oRequest.setVersion(request.getVersion()); oRequest.setTag(request.getTagList().toArray(StringUtils.EMPTY_STRING_ARRAY)); oRequest.setService(request.getServiceList().toArray(StringUtils.EMPTY_STRING_ARRAY)); oRequest.setOpenapi(request.getOpenapi()); OpenAPIFormat format = request.getFormat(); if (request.hasFormat()) { oRequest.setFormat(format.name()); } if (request.hasPretty()) { oRequest.setPretty(request.getPretty()); } String document = openAPIService.getDocument(oRequest); return OpenAPIInfo.newBuilder().setDefinition(document).build(); } } throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode(), "OpenAPI is not available"); } public URL getMetadataUrl() { return metadataUrl; } public void setMetadataUrl(URL metadataUrl) { this.metadataUrl = metadataUrl; } }
MetadataServiceDelegationV2
java
quarkusio__quarkus
extensions/security/deployment/src/main/java/io/quarkus/security/deployment/DotNames.java
{ "start": 358, "end": 1071 }
class ____ { public static final DotName ROLES_ALLOWED = DotName.createSimple(RolesAllowed.class.getName()); public static final DotName AUTHENTICATED = DotName.createSimple(Authenticated.class.getName()); public static final DotName PERMISSIONS_ALLOWED = DotName.createSimple(PermissionsAllowed.class.getName()); public static final DotName DENY_ALL = DotName.createSimple(DenyAll.class.getName()); public static final DotName PERMIT_ALL = DotName.createSimple(PermitAll.class.getName()); // used to make the above annotations appear as @Inherited to Arc public static final DotName INHERITED = DotName.createSimple(Inherited.class.getName()); private DotNames() { } }
DotNames
java
elastic__elasticsearch
x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/querydsl/query/BoolQueryTests.java
{ "start": 982, "end": 6388 }
class ____ extends ESTestCase { static BoolQuery randomBoolQuery(int depth) { return new BoolQuery( SourceTests.randomSource(), randomBoolean(), NestedQueryTests.randomQuery(depth), NestedQueryTests.randomQuery(depth) ); } public void testEqualsAndHashCode() { checkEqualsAndHashCode(randomBoolQuery(5), BoolQueryTests::copy, BoolQueryTests::mutate); } private static BoolQuery copy(BoolQuery query) { return new BoolQuery(query.source(), query.isAnd(), query.queries()); } private static BoolQuery mutate(BoolQuery query) { List<Function<BoolQuery, BoolQuery>> options = Arrays.asList( q -> new BoolQuery(SourceTests.mutate(q.source()), q.isAnd(), left(q), right(q)), q -> new BoolQuery(q.source(), false == q.isAnd(), left(q), right(q)), q -> new BoolQuery(q.source(), q.isAnd(), randomValueOtherThan(left(q), () -> NestedQueryTests.randomQuery(5)), right(q)), q -> new BoolQuery(q.source(), q.isAnd(), left(q), randomValueOtherThan(right(q), () -> NestedQueryTests.randomQuery(5))) ); return randomFrom(options).apply(query); } public void testContainsNestedField() { assertFalse(boolQueryWithoutNestedChildren().containsNestedField(randomAlphaOfLength(5), randomAlphaOfLength(5))); String path = randomAlphaOfLength(5); String field = randomAlphaOfLength(5); assertTrue(boolQueryWithNestedChildren(path, field).containsNestedField(path, field)); } public void testAddNestedField() { Query q = boolQueryWithoutNestedChildren(); assertSame(q, q.addNestedField(randomAlphaOfLength(5), randomAlphaOfLength(5), null, randomBoolean())); String path = randomAlphaOfLength(5); String field = randomAlphaOfLength(5); q = boolQueryWithNestedChildren(path, field); String newField = randomAlphaOfLength(5); boolean hasDocValues = randomBoolean(); Query rewritten = q.addNestedField(path, newField, null, hasDocValues); assertNotSame(q, rewritten); assertTrue(rewritten.containsNestedField(path, newField)); } public void testEnrichNestedSort() { Query q = boolQueryWithoutNestedChildren(); NestedSortBuilder sort = new NestedSortBuilder(randomAlphaOfLength(5)); q.enrichNestedSort(sort); assertNull(sort.getFilter()); String path = randomAlphaOfLength(5); String field = randomAlphaOfLength(5); q = boolQueryWithNestedChildren(path, field); sort = new NestedSortBuilder(path); q.enrichNestedSort(sort); assertNotNull(sort.getFilter()); } private Query boolQueryWithoutNestedChildren() { return new BoolQuery( SourceTests.randomSource(), randomBoolean(), new MatchAll(SourceTests.randomSource()), new MatchAll(SourceTests.randomSource()) ); } private Query boolQueryWithNestedChildren(String path, String field) { NestedQuery match = new NestedQuery( SourceTests.randomSource(), path, singletonMap(field, new SimpleImmutableEntry<>(randomBoolean(), null)), new MatchAll(SourceTests.randomSource()) ); Query matchAll = new MatchAll(SourceTests.randomSource()); Query left; Query right; if (randomBoolean()) { left = match; right = matchAll; } else { left = matchAll; right = match; } return new BoolQuery(SourceTests.randomSource(), randomBoolean(), left, right); } public void testToString() { assertEquals( "BoolQuery@1:2[ExistsQuery@1:2[f1] AND ExistsQuery@1:8[f2]]", new BoolQuery( new Source(1, 1, StringUtils.EMPTY), true, new ExistsQuery(new Source(1, 1, StringUtils.EMPTY), "f1"), new ExistsQuery(new Source(1, 7, StringUtils.EMPTY), "f2") ).toString() ); } public void testNotAllNegated() { var q = new BoolQuery(Source.EMPTY, true, new ExistsQuery(Source.EMPTY, "f1"), new ExistsQuery(Source.EMPTY, "f2")); assertThat(q.negate(Source.EMPTY), equalTo(new NotQuery(Source.EMPTY, q))); } public void testNotSomeNegated() { var q = new BoolQuery( Source.EMPTY, true, new ExistsQuery(Source.EMPTY, "f1"), new NotQuery(Source.EMPTY, new ExistsQuery(Source.EMPTY, "f2")) ); assertThat( q.negate(Source.EMPTY), equalTo( new BoolQuery( Source.EMPTY, false, new NotQuery(Source.EMPTY, new ExistsQuery(Source.EMPTY, "f1")), new ExistsQuery(Source.EMPTY, "f2") ) ) ); } public static Query left(BoolQuery bool) { return indexOf(bool, 0); } public static Query right(BoolQuery bool) { return indexOf(bool, 1); } private static Query indexOf(BoolQuery bool, int index) { List<Query> queries = bool.queries(); assertThat(queries, hasSize(greaterThanOrEqualTo(2))); return queries.get(index); } }
BoolQueryTests
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/BinaryNode.java
{ "start": 570, "end": 1194 }
class ____ extends ExpressionNode { /* ---- begin tree structure ---- */ private ExpressionNode leftNode; private ExpressionNode rightNode; public void setLeftNode(ExpressionNode leftNode) { this.leftNode = leftNode; } public ExpressionNode getLeftNode() { return leftNode; } public void setRightNode(ExpressionNode rightNode) { this.rightNode = rightNode; } public ExpressionNode getRightNode() { return rightNode; } /* ---- end tree structure ---- */ public BinaryNode(Location location) { super(location); } }
BinaryNode
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/util/BestEffortLongFile.java
{ "start": 1709, "end": 1841 }
class ____ differs in that it stores the value as binary data instead * of a textual string. */ @InterfaceAudience.Private public
also
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OidcUserInfoTests.java
{ "start": 5957, "end": 17905 }
class ____ { private static final String DEFAULT_OIDC_USER_INFO_ENDPOINT_URI = "/userinfo"; private static SecurityContextRepository securityContextRepository; public final SpringTestContext spring = new SpringTestContext(this); @Autowired private MockMvc mvc; @Autowired private JwtEncoder jwtEncoder; @Autowired private JwtDecoder jwtDecoder; @Autowired private OAuth2AuthorizationService authorizationService; private static AuthenticationConverter authenticationConverter; private static Consumer<List<AuthenticationConverter>> authenticationConvertersConsumer; private static AuthenticationProvider authenticationProvider; private static Consumer<List<AuthenticationProvider>> authenticationProvidersConsumer; private static AuthenticationSuccessHandler authenticationSuccessHandler; private static AuthenticationFailureHandler authenticationFailureHandler; private static Function<OidcUserInfoAuthenticationContext, OidcUserInfo> userInfoMapper; @BeforeAll public static void init() { securityContextRepository = spy(new HttpSessionSecurityContextRepository()); authenticationConverter = mock(AuthenticationConverter.class); authenticationConvertersConsumer = mock(Consumer.class); authenticationProvider = mock(AuthenticationProvider.class); authenticationProvidersConsumer = mock(Consumer.class); authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); authenticationFailureHandler = mock(AuthenticationFailureHandler.class); userInfoMapper = mock(Function.class); } @BeforeEach public void setup() { reset(securityContextRepository); reset(authenticationConverter); reset(authenticationConvertersConsumer); reset(authenticationProvider); reset(authenticationProvidersConsumer); reset(authenticationSuccessHandler); reset(authenticationFailureHandler); reset(userInfoMapper); } @Test public void requestWhenUserInfoRequestGetThenUserInfoResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off this.mvc.perform(get(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()) .andExpectAll(userInfoResponse()); // @formatter:on } @Test public void requestWhenUserInfoRequestPostThenUserInfoResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off this.mvc.perform(post(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()) .andExpectAll(userInfoResponse()); // @formatter:on } @Test public void requestWhenUserInfoRequestIncludesIssuerPathThenUserInfoResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); String issuer = "https://example.com:8443/issuer1"; OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off this.mvc.perform(get(issuer.concat(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()) .andExpectAll(userInfoResponse()); // @formatter:on } @Test public void requestWhenUserInfoEndpointCustomizedThenUsed() throws Exception { this.spring.register(CustomUserInfoConfiguration.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); given(userInfoMapper.apply(any())).willReturn(createUserInfo()); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off this.mvc.perform(get(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()); // @formatter:on verify(userInfoMapper).apply(any()); verify(authenticationConverter).convert(any()); verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); verifyNoInteractions(authenticationFailureHandler); ArgumentCaptor<List<AuthenticationProvider>> authenticationProvidersCaptor = ArgumentCaptor .forClass(List.class); verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List<AuthenticationProvider> authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(2) .allMatch((provider) -> provider == authenticationProvider || provider instanceof OidcUserInfoAuthenticationProvider); ArgumentCaptor<List<AuthenticationConverter>> authenticationConvertersCaptor = ArgumentCaptor .forClass(List.class); verify(authenticationConvertersConsumer).accept(authenticationConvertersCaptor.capture()); List<AuthenticationConverter> authenticationConverters = authenticationConvertersCaptor.getValue(); assertThat(authenticationConverters).hasSize(2).allMatch(AuthenticationConverter.class::isInstance); } @Test public void requestWhenUserInfoEndpointCustomizedWithAuthenticationProviderThenUsed() throws Exception { this.spring.register(CustomUserInfoConfiguration.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); given(authenticationProvider.supports(eq(OidcUserInfoAuthenticationToken.class))).willReturn(true); String tokenValue = authorization.getAccessToken().getToken().getTokenValue(); Jwt jwt = this.jwtDecoder.decode(tokenValue); OidcUserInfoAuthenticationToken oidcUserInfoAuthentication = new OidcUserInfoAuthenticationToken( new JwtAuthenticationToken(jwt), createUserInfo()); given(authenticationProvider.authenticate(any())).willReturn(oidcUserInfoAuthentication); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off this.mvc.perform(get(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()); // @formatter:on verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); verify(authenticationProvider).authenticate(any()); verifyNoInteractions(authenticationFailureHandler); verifyNoInteractions(userInfoMapper); } @Test public void requestWhenUserInfoEndpointCustomizedWithAuthenticationFailureHandlerThenUsed() throws Exception { this.spring.register(CustomUserInfoConfiguration.class).autowire(); given(userInfoMapper.apply(any())).willReturn(createUserInfo()); willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().write("unauthorized"); return null; }).given(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); OAuth2AccessToken accessToken = createAuthorization().getAccessToken().getToken(); // @formatter:off this.mvc.perform(get(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is4xxClientError()); // @formatter:on verify(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); verifyNoInteractions(authenticationSuccessHandler); verifyNoInteractions(userInfoMapper); } // gh-482 @Test public void requestWhenUserInfoRequestThenBearerTokenAuthenticationNotPersisted() throws Exception { this.spring.register(AuthorizationServerConfigurationWithSecurityContextRepository.class).autowire(); OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off MvcResult mvcResult = this.mvc.perform(get(DEFAULT_OIDC_USER_INFO_ENDPOINT_URI) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue())) .andExpect(status().is2xxSuccessful()) .andExpectAll(userInfoResponse()) .andReturn(); // @formatter:on org.springframework.security.core.context.SecurityContext securityContext = securityContextRepository .loadDeferredContext(mvcResult.getRequest()) .get(); assertThat(securityContext.getAuthentication()).isNull(); } private static ResultMatcher[] userInfoResponse() { // @formatter:off return new ResultMatcher[] { jsonPath("sub").value("user1"), jsonPath("name").value("First Last"), jsonPath("given_name").value("First"), jsonPath("family_name").value("Last"), jsonPath("middle_name").value("Middle"), jsonPath("nickname").value("User"), jsonPath("preferred_username").value("user"), jsonPath("profile").value("https://example.com/user1"), jsonPath("picture").value("https://example.com/user1.jpg"), jsonPath("website").value("https://example.com"), jsonPath("email").value("user1@example.com"), jsonPath("email_verified").value("true"), jsonPath("gender").value("female"), jsonPath("birthdate").value("1970-01-01"), jsonPath("zoneinfo").value("Europe/Paris"), jsonPath("locale").value("en-US"), jsonPath("phone_number").value("+1 (604) 555-1234;ext=5678"), jsonPath("phone_number_verified").value("false"), jsonPath("address.formatted").value("Champ de Mars\n5 Av. Anatole France\n75007 Paris\nFrance"), jsonPath("updated_at").value("1970-01-01T00:00:00Z") }; // @formatter:on } private OAuth2Authorization createAuthorization() { JwsHeader headers = JwsHeader.with(SignatureAlgorithm.RS256).build(); // @formatter:off JwtClaimsSet claimSet = JwtClaimsSet.builder() .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); // @formatter:on Jwt jwt = this.jwtEncoder.encode(JwtEncoderParameters.from(headers, claimSet)); Instant now = Instant.now(); Set<String> scopes = new HashSet<>(Arrays.asList(OidcScopes.OPENID, OidcScopes.ADDRESS, OidcScopes.EMAIL, OidcScopes.PHONE, OidcScopes.PROFILE)); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), now, now.plusSeconds(300), scopes); OidcIdToken idToken = OidcIdToken.withTokenValue("id-token") .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); return TestOAuth2Authorizations.authorization().accessToken(accessToken).token(idToken).build(); } private static OidcUserInfo createUserInfo() { // @formatter:off return OidcUserInfo.builder() .subject("user1") .name("First Last") .givenName("First") .familyName("Last") .middleName("Middle") .nickname("User") .preferredUsername("user") .profile("https://example.com/user1") .picture("https://example.com/user1.jpg") .website("https://example.com") .email("user1@example.com") .emailVerified(true) .gender("female") .birthdate("1970-01-01") .zoneinfo("Europe/Paris") .locale("en-US") .phoneNumber("+1 (604) 555-1234;ext=5678") .phoneNumberVerified(false) .claim("address", Collections.singletonMap("formatted", "Champ de Mars\n5 Av. Anatole France\n75007 Paris\nFrance")) .updatedAt("1970-01-01T00:00:00Z") .build(); // @formatter:on } @EnableWebSecurity @Configuration(proxyBeanMethods = false) static
OidcUserInfoTests
java
quarkusio__quarkus
extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiBuildTimeExcludedClassTestCase.java
{ "start": 4287, "end": 4418 }
class ____ { @GET public String endpoint() { return ""; } } }
UnlessBuildPropertyBarBazIsFalse
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/http/sender/RequestExecutorService.java
{ "start": 29853, "end": 30055 }
class ____ signals in the request queue"); } @Override public RequestManager getRequestManager() { throw new UnsupportedOperationException("NoopTask is a pure marker
for
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopIntFloatAggregator.java
{ "start": 1187, "end": 1418 }
class ____ generated. Edit `X-TopAggregator.java.st` to edit this file. * </p> */ @Aggregator({ @IntermediateState(name = "top", type = "INT_BLOCK"), @IntermediateState(name = "output", type = "FLOAT_BLOCK") }) @GroupingAggregator
is
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/issues/AdviceWithTransactionIssueTest.java
{ "start": 1239, "end": 2833 }
class ____ extends SpringTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/issues/AdviceWithTransactionIssueTest.xml"); } @Test public void testAdviceWithWeaveById() throws Exception { AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveById("mock-b*").after().to("mock:last"); } }); context.start(); MockEndpoint mockLast = getMockEndpoint("mock:last"); mockLast.expectedBodiesReceived("bar"); mockLast.setExpectedMessageCount(1); template.sendBody("seda:start", "bar"); assertMockEndpointsSatisfied(); } @Test public void testAdviceWithAddLast() throws Exception { AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveAddLast().to("mock:last"); } }); context.start(); MockEndpoint mockLast = getMockEndpoint("mock:last"); mockLast.expectedBodiesReceived("bar"); mockLast.setExpectedMessageCount(1); template.sendBody("seda:start", "bar"); assertMockEndpointsSatisfied(); } }
AdviceWithTransactionIssueTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/FlinkEndpointBuilderFactory.java
{ "start": 1437, "end": 1558 }
interface ____ { /** * Builder for endpoint for the Flink component. */ public
FlinkEndpointBuilderFactory
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerTests.java
{ "start": 1870, "end": 8838 }
class ____ { private static final String SET_UP_OUTSIDE_OF_STEL = "setUpOutsideOfStel"; private final WebApplicationContext wac = mock(); private final MockServletContext mockServletContext = new MockServletContext(); private final TestContext testContext = mock(); private final ServletTestExecutionListener listener = new ServletTestExecutionListener(); @BeforeEach void setUp() { given(wac.getServletContext()).willReturn(mockServletContext); given(testContext.getApplicationContext()).willReturn(wac); MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext); MockHttpServletResponse response = new MockHttpServletResponse(); ServletWebRequest servletWebRequest = new ServletWebRequest(request, response); request.setAttribute(SET_UP_OUTSIDE_OF_STEL, "true"); RequestContextHolder.setRequestAttributes(servletWebRequest); assertSetUpOutsideOfStelAttributeExists(); } @Test void standardApplicationContext() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(getClass()); given(testContext.getApplicationContext()).willReturn(mock()); listener.beforeTestClass(testContext); assertSetUpOutsideOfStelAttributeExists(); listener.prepareTestInstance(testContext); assertSetUpOutsideOfStelAttributeExists(); listener.beforeTestMethod(testContext); assertSetUpOutsideOfStelAttributeExists(); listener.afterTestMethod(testContext); assertSetUpOutsideOfStelAttributeExists(); } @Test void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class); RequestContextHolder.resetRequestAttributes(); assertRequestAttributesDoNotExist(); listener.beforeTestClass(testContext); listener.prepareTestInstance(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null); listener.beforeTestMethod(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); listener.afterTestMethod(testContext); verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); assertRequestAttributesDoNotExist(); } @Test void legacyWebTestCaseWithPresetRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class); listener.beforeTestClass(testContext); assertSetUpOutsideOfStelAttributeExists(); listener.prepareTestInstance(testContext); assertSetUpOutsideOfStelAttributeExists(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null); listener.beforeTestMethod(testContext); assertSetUpOutsideOfStelAttributeExists(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null); listener.afterTestMethod(testContext); verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); assertSetUpOutsideOfStelAttributeExists(); } @Test void atWebAppConfigTestCaseWithoutExistingRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(AtWebAppConfigWebTestCase.class); RequestContextHolder.resetRequestAttributes(); listener.beforeTestClass(testContext); assertRequestAttributesDoNotExist(); assertWebAppConfigTestCase(); } @Test void atWebAppConfigTestCaseWithPresetRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(AtWebAppConfigWebTestCase.class); listener.beforeTestClass(testContext); assertRequestAttributesExist(); assertWebAppConfigTestCase(); } /** * @since 4.3 */ @Test void activateListenerWithoutExistingRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(NoAtWebAppConfigWebTestCase.class); given(testContext.getAttribute(ServletTestExecutionListener.ACTIVATE_LISTENER)).willReturn(true); RequestContextHolder.resetRequestAttributes(); listener.beforeTestClass(testContext); assertRequestAttributesDoNotExist(); assertWebAppConfigTestCase(); } private RequestAttributes assertRequestAttributesExist() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); assertThat(requestAttributes).as("request attributes should exist").isNotNull(); return requestAttributes; } private void assertRequestAttributesDoNotExist() { assertThat(RequestContextHolder.getRequestAttributes()).as("request attributes should not exist").isNull(); } private void assertSetUpOutsideOfStelAttributeExists() { RequestAttributes requestAttributes = assertRequestAttributesExist(); Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST); assertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute").isNotNull(); } private void assertSetUpOutsideOfStelAttributeDoesNotExist() { RequestAttributes requestAttributes = assertRequestAttributesExist(); Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST); assertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute").isNull(); } private void assertWebAppConfigTestCase() throws Exception { listener.prepareTestInstance(testContext); assertRequestAttributesExist(); assertSetUpOutsideOfStelAttributeDoesNotExist(); verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE); listener.beforeTestMethod(testContext); assertRequestAttributesExist(); assertSetUpOutsideOfStelAttributeDoesNotExist(); verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); listener.afterTestMethod(testContext); verify(testContext).removeAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); verify(testContext).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); assertRequestAttributesDoNotExist(); } static
ServletTestExecutionListenerTests
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/LdifComponentBuilderFactory.java
{ "start": 3937, "end": 4695 }
class ____ extends AbstractComponentBuilder<LdifComponent> implements LdifComponentBuilder { @Override protected LdifComponent buildConcreteComponent() { return new LdifComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "lazyStartProducer": ((LdifComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((LdifComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
LdifComponentBuilderImpl
java
apache__camel
dsl/camel-endpointdsl/src/test/java/org/apache/camel/builder/endpoint/FileConsumeCharsetTest.java
{ "start": 1202, "end": 2649 }
class ____ extends BaseEndpointDslTest { private static final String TEST_DATA_DIR = BaseEndpointDslTest.generateUniquePath(FileConsumeCharsetTest.class); @Override public void doPreSetup() { TestSupport.deleteDirectory(TEST_DATA_DIR); } @Override protected void doPostSetup() { template.sendBodyAndHeader("file://" + TEST_DATA_DIR + "?charset=UTF-8", "Hello World \u4f60\u597d", Exchange.FILE_NAME, "report.txt"); } @Test public void testConsumeAndDelete() throws Exception { NotifyBuilder oneExchangeDone = new NotifyBuilder(context).whenDone(1).create(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World \u4f60\u597d"); MockEndpoint.assertIsSatisfied(context); oneExchangeDone.matchesWaitTime(); // file should not exists assertFalse(new File(TEST_DATA_DIR, "report.txt").exists(), "File should been deleted"); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new EndpointRouteBuilder() { public void configure() throws Exception { from(file(TEST_DATA_DIR).initialDelay(0).delay(10).fileName("report.txt").delete(true).charset("UTF-8")) .convertBodyTo(String.class) .to(mock("result")); } }; } }
FileConsumeCharsetTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java
{ "start": 1307, "end": 2249 }
class ____ { @Test void getTargetObjectForNull() { assertThatIllegalArgumentException().isThrownBy(() -> getTargetObject(null)); } @Test void getTargetObjectForNonProxiedObject() { Foo target = getTargetObject(foo); assertThat(target).isSameAs(foo); } @Test void getTargetObjectWrappedInSingleJdkDynamicProxy() { Foo target = getTargetObject(jdkProxy(foo)); assertThat(target).isSameAs(foo); } @Test void getTargetObjectWrappedInSingleCglibProxy() { Foo target = getTargetObject(cglibProxy(foo)); assertThat(target).isSameAs(foo); } @Test void getTargetObjectWrappedInDoubleJdkDynamicProxy() { Foo target = getTargetObject(jdkProxy(jdkProxy(foo))); assertThat(target).isNotSameAs(foo); } @Test void getTargetObjectWrappedInDoubleCglibProxy() { Foo target = getTargetObject(cglibProxy(cglibProxy(foo))); assertThat(target).isNotSameAs(foo); } } @Nested
GetTargetObject
java
google__dagger
javatests/dagger/internal/codegen/ComponentBuilderTest.java
{ "start": 2611, "end": 3460 }
interface ____ {", " Builder setTestModule(TestModule testModule);", " TestComponent create();", " }", "}"); CompilerTests.daggerCompiler(moduleFile, componentFile) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource(goldenFileRule.goldenSource("test/DaggerTestComponent")); }); } @Test public void testSetterMethodWithMoreThanOneArgFails() { Source componentFile = CompilerTests.javaSource( "test.SimpleComponent", "package test;", "", "import dagger.Component;", "import javax.inject.Provider;", "", "@Component", "abstract
Builder
java
apache__camel
components/camel-spring-parent/camel-spring-ai/camel-spring-ai-vector-store/src/main/java/org/apache/camel/component/springai/vectorstore/SpringAiVectorStoreConfiguration.java
{ "start": 1149, "end": 3265 }
class ____ implements Cloneable { @Metadata(required = true, autowired = true) @UriParam private VectorStore vectorStore; @UriParam(defaultValue = "ADD") private SpringAiVectorStoreOperation operation = SpringAiVectorStoreOperation.ADD; @UriParam(defaultValue = "5") private int topK = 5; @UriParam(defaultValue = "0.0") private double similarityThreshold = 0.0; @UriParam private String filterExpression; public VectorStore getVectorStore() { return vectorStore; } /** * The {@link VectorStore} to use for vector operations. */ public void setVectorStore(VectorStore vectorStore) { this.vectorStore = vectorStore; } public SpringAiVectorStoreOperation getOperation() { return operation; } /** * The operation to perform on the vector store (ADD, DELETE, SIMILARITY_SEARCH). */ public void setOperation(SpringAiVectorStoreOperation operation) { this.operation = operation; } public int getTopK() { return topK; } /** * The maximum number of similar documents to return for similarity search. */ public void setTopK(int topK) { this.topK = topK; } public double getSimilarityThreshold() { return similarityThreshold; } /** * The minimum similarity score threshold (0-1) for similarity search. */ public void setSimilarityThreshold(double similarityThreshold) { this.similarityThreshold = similarityThreshold; } public String getFilterExpression() { return filterExpression; } /** * Filter expression for metadata-based filtering in searches. */ public void setFilterExpression(String filterExpression) { this.filterExpression = filterExpression; } public SpringAiVectorStoreConfiguration copy() { try { return (SpringAiVectorStoreConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
SpringAiVectorStoreConfiguration
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/template/Source.java
{ "start": 229, "end": 924 }
class ____ { private String stringPropX; private Integer integerPropX; private NestedSource nestedSourceProp; public String getStringPropX() { return stringPropX; } public void setStringPropX(String stringPropX) { this.stringPropX = stringPropX; } public Integer getIntegerPropX() { return integerPropX; } public void setIntegerPropX(Integer integerPropX) { this.integerPropX = integerPropX; } public NestedSource getNestedSourceProp() { return nestedSourceProp; } public void setNestedSourceProp(NestedSource nestedSourceProp) { this.nestedSourceProp = nestedSourceProp; } }
Source
java
apache__camel
components/camel-zookeeper/src/test/java/org/apache/camel/component/zookeeper/NaturalSortComparatorTest.java
{ "start": 1135, "end": 2076 }
class ____ { @Test public void testSortOrder() { List<String> sorted = Arrays .asList(new String[] { "0", "1", "3", "4.0", "11", "30", "55", "225", "333", "camel-2.1.0", "camel-2.1.1", "camel-2.1.1-SNAPSHOT", "camel-2.2.0" }); List<String> unsorted = new ArrayList<>(sorted); Collections.shuffle(unsorted); Collections.sort(unsorted, new NaturalSortComparator()); compareLists(sorted, unsorted); Collections.shuffle(unsorted); Collections.sort(unsorted, new NaturalSortComparator(Order.Descending)); Collections.reverse(sorted); compareLists(sorted, unsorted); } private void compareLists(List<String> sorted, List<String> unsorted) { for (int x = 0; x < unsorted.size(); x++) { assertEquals(sorted.get(x), unsorted.get(x)); } } }
NaturalSortComparatorTest
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/controllers/v3/InstanceControllerV3.java
{ "start": 3627, "end": 14059 }
class ____ { private final SwitchDomain switchDomain; private final InstanceOperatorClientImpl instanceService; private final CatalogService catalogService; public InstanceControllerV3(SwitchDomain switchDomain, InstanceOperatorClientImpl instanceService, CatalogService catalogService) { this.switchDomain = switchDomain; this.instanceService = instanceService; this.catalogService = catalogService; } /** * Register new instance. */ @CanDistro @PostMapping @TpsControl(pointName = "NamingInstanceRegister", name = "HttpNamingInstanceRegister") @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<String> register(InstanceForm instanceForm) throws NacosException { // check param instanceForm.validate(); NamingRequestUtil.checkWeight(instanceForm.getWeight()); // build instance Instance instance = InstanceUtil.buildInstance(instanceForm, switchDomain.isDefaultInstanceEphemeral()); String namespaceId = instanceForm.getNamespaceId(); String groupName = instanceForm.getGroupName(); String serviceName = instanceForm.getServiceName(); instanceService.registerInstance(namespaceId, groupName, serviceName, instance); NotifyCenter.publishEvent( new RegisterInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), false, namespaceId, groupName, serviceName, instance.getIp(), instance.getPort())); return Result.success("ok"); } /** * Deregister instances. */ @CanDistro @DeleteMapping @TpsControl(pointName = "NamingInstanceDeregister", name = "HttpNamingInstanceDeregister") @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<String> deregister(InstanceForm instanceForm) throws NacosException { // check param instanceForm.validate(); // build instance Instance instance = InstanceUtil.buildInstance(instanceForm, switchDomain.isDefaultInstanceEphemeral()); instanceService.removeInstance(instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), instance); NotifyCenter.publishEvent( new DeregisterInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), false, DeregisterInstanceReason.REQUEST, instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(), instance.getPort())); return Result.success("ok"); } /** * Update instance. */ @CanDistro @PutMapping @TpsControl(pointName = "NamingInstanceUpdate", name = "HttpNamingInstanceUpdate") @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<String> update(InstanceForm instanceForm) throws NacosException { // check param instanceForm.validate(); NamingRequestUtil.checkWeight(instanceForm.getWeight()); // build instance Instance instance = InstanceUtil.buildInstance(instanceForm, switchDomain.isDefaultInstanceEphemeral()); instanceService.updateInstance(instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), instance); NotifyCenter.publishEvent( new UpdateInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(), instance.getPort(), instance.getMetadata())); return Result.success("ok"); } /** * Batch update instance's metadata. old key exist = update, old key not exist = add. */ @CanDistro @PutMapping(value = "/metadata/batch") @TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate") @ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class) @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<InstanceMetadataBatchResult> batchUpdateInstanceMetadata(InstanceMetadataBatchOperationForm form) throws NacosException { form.validate(); List<Instance> targetInstances = parseBatchInstances(form.getInstances()); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata()); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form), form.getConsistencyType(), targetInstances); List<String> operatedInstances = instanceService.batchUpdateMetadata(form.getNamespaceId(), instanceOperationInfo, targetMetadata); ArrayList<String> ipList = new ArrayList<>(operatedInstances); return Result.success(new InstanceMetadataBatchResult(ipList)); } /** * Batch delete instance's metadata. old key exist = delete, old key not exist = not operate */ @CanDistro @DeleteMapping("/metadata/batch") @TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate") @ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class) @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<InstanceMetadataBatchResult> batchDeleteInstanceMetadata(InstanceMetadataBatchOperationForm form) throws NacosException { form.validate(); List<Instance> targetInstances = parseBatchInstances(form.getInstances()); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata()); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form), form.getConsistencyType(), targetInstances); List<String> operatedInstances = instanceService.batchDeleteMetadata(form.getNamespaceId(), instanceOperationInfo, targetMetadata); ArrayList<String> ipList = new ArrayList<>(operatedInstances); return Result.success(new InstanceMetadataBatchResult(ipList)); } private InstanceOperationInfo buildOperationInfo(String serviceName, String consistencyType, List<Instance> instances) { if (!CollectionUtils.isEmpty(instances)) { for (Instance instance : instances) { if (StringUtils.isBlank(instance.getClusterName())) { instance.setClusterName(DEFAULT_CLUSTER_NAME); } } } return new InstanceOperationInfo(serviceName, consistencyType, instances); } private List<Instance> parseBatchInstances(String instances) { try { return JacksonUtils.toObj(instances, new TypeReference<List<Instance>>() { }); } catch (Exception e) { Loggers.SRV_LOG.warn("UPDATE-METADATA: Param 'instances' is illegal, ignore this operation", e); } return Collections.emptyList(); } /** * Partial update instance. */ @CanDistro @PutMapping(value = "/partial") @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<String> partialUpdateInstance(InstanceForm instanceForm) throws Exception { instanceForm.validate(); InstancePatchObject patchObject = new InstancePatchObject(instanceForm.getClusterName(), instanceForm.getIp(), instanceForm.getPort()); String metadata = instanceForm.getMetadata(); if (StringUtils.isNotBlank(metadata)) { patchObject.setMetadata(UtilsAndCommons.parseMetadata(metadata)); } Double weight = instanceForm.getWeight(); if (weight != null) { NamingRequestUtil.checkWeight(weight); patchObject.setWeight(weight); } Boolean enabled = instanceForm.getEnabled(); if (enabled != null) { patchObject.setEnabled(enabled); } instanceService.patchInstance(instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), patchObject); return Result.success("ok"); } /** * Get all instance of input service. */ @GetMapping("/list") @TpsControl(pointName = "NamingServiceSubscribe", name = "HttpNamingServiceSubscribe") @ExtractorManager.Extractor(httpExtractor = NamingInstanceListHttpParamExtractor.class) @Secured(action = ActionTypes.READ, apiType = ApiType.ADMIN_API) public Result<List<? extends Instance>> list(InstanceListForm instanceListForm) throws NacosException { instanceListForm.validate(); List<? extends Instance> instances = catalogService.listInstances(instanceListForm.getNamespaceId(), instanceListForm.getGroupName(), instanceListForm.getServiceName(), instanceListForm.getClusterName()); if (instanceListForm.getHealthyOnly()) { instances = instances.stream().filter(Instance::isHealthy).toList(); } return Result.success(instances); } /** * Get detail information of specified instance. */ @GetMapping @TpsControl(pointName = "NamingInstanceQuery", name = "HttpNamingInstanceQuery") @Secured(action = ActionTypes.WRITE, apiType = ApiType.ADMIN_API) public Result<Instance> detail(InstanceForm instanceForm) throws NacosException { instanceForm.validate(); String namespaceId = instanceForm.getNamespaceId(); String clusterName = instanceForm.getClusterName(); String ip = instanceForm.getIp(); int port = instanceForm.getPort(); Instance instance = instanceService.getInstance(namespaceId, instanceForm.getGroupName(), instanceForm.getServiceName(), clusterName, ip, port); return Result.success(instance); } private String buildCompositeServiceName(InstanceMetadataBatchOperationForm form) { return NamingUtils.getGroupedName(form.getServiceName(), form.getGroupName()); } }
InstanceControllerV3
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateIndexTest12.java
{ "start": 967, "end": 3478 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE BITMAP INDEX product_bm_ix \n" + " ON hash_products(list_price)\n" + " TABLESPACE tbs_1\n" + " LOCAL(PARTITION ix_p1 TABLESPACE tbs_02,\n" + " PARTITION ix_p2,\n" + " PARTITION ix_p3 TABLESPACE tbs_03,\n" + " PARTITION ix_p4,\n" + " PARTITION ix_p5 TABLESPACE tbs_04 );\n"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals("CREATE BITMAP INDEX product_bm_ix ON hash_products(list_price)\n" + "TABLESPACE tbs_1\n" + "LOCAL (\n" + "\tPARTITION ix_p1\n" + "\t\tTABLESPACE tbs_02,\n" + "\tPARTITION ix_p2,\n" + "\tPARTITION ix_p3\n" + "\t\tTABLESPACE tbs_03,\n" + "\tPARTITION ix_p4,\n" + "\tPARTITION ix_p5\n" + "\t\tTABLESPACE tbs_04\n" + ");", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("hash_products"))); assertEquals(1, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("xwarehouses", "sales_rep_id"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleCreateIndexTest12
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/plugins/UberModuleClassLoaderTests.java
{ "start": 26995, "end": 30477 }
class ____ our ubermodule may use SPI to load a service. Our test scenario needs to work out the following four * conditions: * * 1. Service defined in package exported in parent layer. * 2. Service defined in a compile-time dependency, optionally present at runtime. * 3. Service defined in modular jar in uberjar * 4. Service defined in non-modular jar in uberjar * * In all these cases, our ubermodule should declare that it uses each service *available at runtime*, and that * it provides these services with the correct providers. * * We create a jar for each scenario, plus "service caller" jar with a demo class, then * create an UberModuleClassLoader for the relevant jars. */ private static UberModuleClassLoader getServiceTestLoader(boolean includeOptionalDeps) throws IOException { Path libDir = createTempDir("libs"); Path parentJar = createRequiredJarForParentLayer(libDir); Path optionalJar = createOptionalJarForParentLayer(libDir); Set<String> moduleNames = includeOptionalDeps ? Set.of("p.required", "p.optional") : Set.of("p.required"); ModuleFinder parentModuleFinder = includeOptionalDeps ? ModuleFinder.of(parentJar, optionalJar) : ModuleFinder.of(parentJar); Configuration parentLayerConfiguration = ModuleLayer.boot() .configuration() .resolve(parentModuleFinder, ModuleFinder.of(), moduleNames); URLClassLoader parentLoader = new URLClassLoader(new URL[] { pathToUrlUnchecked(parentJar) }); loaders.add(parentLoader); URLClassLoader optionalLoader = new URLClassLoader(new URL[] { pathToUrlUnchecked(optionalJar) }, parentLoader); loaders.add(optionalLoader); ModuleLayer parentLayer = ModuleLayer.defineModules(parentLayerConfiguration, List.of(ModuleLayer.boot()), (String moduleName) -> { if (moduleName.equals("p.required")) { return parentLoader; } else if (includeOptionalDeps && moduleName.equals("p.optional")) { return optionalLoader; } return null; }).layer(); // jars for the ubermodule Path modularJar = createModularizedJarForBundle(libDir); Path nonModularJar = createNonModularizedJarForBundle(libDir, parentJar, optionalJar, modularJar); Path serviceCallerJar = createServiceCallingJarForBundle(libDir, parentJar, optionalJar, modularJar, nonModularJar); Set<Path> jarPaths = new HashSet<>(Set.of(modularJar, nonModularJar, serviceCallerJar)); return UberModuleClassLoader.getInstance( parentLayer.findLoader(includeOptionalDeps ? "p.optional" : "p.required"), parentLayer, MODULE_NAME, jarPaths.stream().map(UberModuleClassLoaderTests::pathToUrlUnchecked).collect(Collectors.toSet()), Set.of(), Set.of() ); } private static Path createServiceCallingJarForBundle(Path libDir, Path parentJar, Path optionalJar, Path modularJar, Path nonModularJar) throws IOException { String serviceCaller = """ package q.caller; import p.optional.AnimalService; import p.required.LetterService; import q.jar.one.NumberService; import q.jar.two.FooBarService; import java.util.ServiceLoader; import java.util.stream.Collectors; public
in
java
alibaba__nacos
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigTagsRelationMapper.java
{ "start": 1222, "end": 6654 }
interface ____ extends Mapper { /** * Get the count of config info. * The default sql: * SELECT count(*) FROM config_info WHERE ... * * @param context The map of params, the key is the parameter name(dataId, groupId, tenantId, appName, startTime, * endTime, content), the value is the key's value. * @return The sql of get config info. */ default MapperResult findConfigInfo4PageCountRows(final MapperContext context) { final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); List<Object> paramList = new ArrayList<>(); StringBuilder where = new StringBuilder(" WHERE "); final String sqlCount = "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id"; where.append(" a.tenant_id=? "); paramList.add(tenantId); if (StringUtils.isNotBlank(dataId)) { where.append(" AND a.data_id=? "); paramList.add(dataId); } if (StringUtils.isNotBlank(group)) { where.append(" AND a.group_id=? "); paramList.add(group); } if (StringUtils.isNotBlank(appName)) { where.append(" AND a.app_name=? "); paramList.add(appName); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); paramList.add(content); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagArr.length; i++) { if (i != 0) { where.append(", "); } where.append('?'); paramList.add(tagArr[i]); } where.append(") "); return new MapperResult(sqlCount + where, paramList); } /** * Find config info. * The default sql: * SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN * config_tags_relation b ON a.id=b.i ... * * @param context The keys and values are dataId and group. * @return The sql of finding config info. */ MapperResult findConfigInfo4PageFetchRows(final MapperContext context); /** * Get the count of config information by config tags relation. * The default sql: * SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id * * @param context the keys and values are dataId and group. * @return The sql of getting the count of config information. */ default MapperResult findConfigInfoLike4PageCountRows(final MapperContext context) { final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); WhereBuilder where = new WhereBuilder("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id"); where.like("a.tenant_id", tenantId); if (StringUtils.isNotBlank(dataId)) { where.and().like("a.data_id", dataId); } if (StringUtils.isNotBlank(group)) { where.and().like("a.group_id", group); } if (StringUtils.isNotBlank(appName)) { where.and().eq("a.app_name", appName); } if (StringUtils.isNotBlank(content)) { where.and().like("a.content", content); } if (!ArrayUtils.isEmpty(tagArr)) { where.and().startParentheses(); for (int i = 0; i < tagArr.length; i++) { if (i != 0) { where.or(); } where.like("b.tag_name", tagArr[i]); } where.endParentheses(); } if (!ArrayUtils.isEmpty(types)) { where.and().in("a.type", types); } return where.build(); } /** * Query config info. * The default sql: * SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content * FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id * * @param context the keys and values are dataId and group. * @return The sql of querying config info. */ MapperResult findConfigInfoLike4PageFetchRows(final MapperContext context); /** * 获取返回表名. * * @return 表名 */ default String getTableName() { return TableConstant.CONFIG_TAGS_RELATION; } }
ConfigTagsRelationMapper
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/ChainedDriver.java
{ "start": 1794, "end": 1928 }
interface ____ be implemented by drivers that do not run in an own task context, but are * chained to other tasks. */ public abstract
to
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/io/benchmark/SerializingLongReceiver.java
{ "start": 1189, "end": 2249 }
class ____ extends ReceiverThread { private final MutableRecordReader<LongValue> reader; @SuppressWarnings("WeakerAccess") public SerializingLongReceiver(InputGate inputGate, int expectedRepetitionsOfExpectedRecord) { super(expectedRepetitionsOfExpectedRecord); this.reader = new MutableRecordReader<>( inputGate, new String[] {EnvironmentInformation.getTemporaryFileDirectory()}); } @Override protected void readRecords(long lastExpectedRecord) throws Exception { LOG.debug("readRecords(lastExpectedRecord = {})", lastExpectedRecord); final LongValue value = new LongValue(); while (running && reader.next(value)) { final long ts = value.getValue(); if (ts == lastExpectedRecord) { expectedRecordCounter++; if (expectedRecordCounter == expectedRepetitionsOfExpectedRecord) { break; } } } } }
SerializingLongReceiver
java
apache__camel
components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyComponent.java
{ "start": 1549, "end": 8208 }
class ____ extends DefaultComponent implements SSLContextParametersAware { private static final Logger LOG = LoggerFactory.getLogger(NettyComponent.class); @Metadata(description = "To use the NettyConfiguration as configuration when creating endpoints") private NettyConfiguration configuration = new NettyConfiguration(); @Metadata(label = "consumer,advanced", description = "Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus" + " 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then" + " will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17." + " This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure" + " ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected.") private int maximumPoolSize; @Metadata(label = "consumer,advanced", description = "To use the given custom EventExecutorGroup.") private volatile EventExecutorGroup executorService; @Metadata(label = "security", description = "Enable usage of global SSL context parameters.") private boolean useGlobalSslContextParameters; public NettyComponent() { } public NettyComponent(Class<? extends Endpoint> endpointClass) { } public NettyComponent(CamelContext context) { super(context); } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus * 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then * will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. * * This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure * ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be * affected. */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { NettyConfiguration config = configuration.copy(); config = parseConfiguration(config, remaining, parameters); // merge any custom bootstrap configuration on the config NettyServerBootstrapConfiguration bootstrapConfiguration = resolveAndRemoveReferenceParameter(parameters, "bootstrapConfiguration", NettyServerBootstrapConfiguration.class); if (bootstrapConfiguration != null) { Map<String, Object> options = new HashMap<>(); BeanIntrospection beanIntrospection = PluginHelper.getBeanIntrospection(getCamelContext()); if (beanIntrospection.getProperties(bootstrapConfiguration, options, null, false)) { PropertyBindingSupport.bindProperties(getCamelContext(), config, options); } } if (config.getSslContextParameters() == null) { config.setSslContextParameters(retrieveGlobalSslContextParameters()); } // validate config config.validateConfiguration(); NettyEndpoint nettyEndpoint = new NettyEndpoint(uri, this, config); setProperties(nettyEndpoint, parameters); return nettyEndpoint; } /** * Parses the configuration * * @return the parsed and valid configuration to use */ protected NettyConfiguration parseConfiguration( NettyConfiguration configuration, String remaining, Map<String, Object> parameters) throws Exception { configuration.parseURI(new URI(remaining), parameters, this, "tcp", "udp"); return configuration; } public NettyConfiguration getConfiguration() { return configuration; } /** * To use the NettyConfiguration as configuration when creating endpoints. */ public void setConfiguration(NettyConfiguration configuration) { this.configuration = configuration; } /** * To use the given EventExecutorGroup. */ public void setExecutorService(EventExecutorGroup executorService) { this.executorService = executorService; } @Override public boolean isUseGlobalSslContextParameters() { return this.useGlobalSslContextParameters; } /** * Enable usage of global SSL context parameters. */ @Override public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) { this.useGlobalSslContextParameters = useGlobalSslContextParameters; } public EventExecutorGroup getExecutorService() { return executorService; } @Override protected void doStart() throws Exception { //Only setup the executorService if it is needed if (configuration.isUsingExecutorService() && executorService == null) { int netty = SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2); // we want one more thread than netty uses for its event loop // and if there is a custom size for maximum pool size then use it, unless netty event loops has more threads // and therefore we use math.max to find the highest value int threads = Math.max(maximumPoolSize, netty + 1); executorService = NettyHelper.createExecutorGroup(getCamelContext(), "NettyConsumerExecutorGroup", threads); LOG.info("Creating shared NettyConsumerExecutorGroup with {} threads", threads); } super.doStart(); } @Override protected void doStop() throws Exception { //Only shutdown the executorService if it is created by netty component if (configuration.isUsingExecutorService() && executorService != null) { getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService); executorService = null; } //shutdown workerPool if configured if (configuration.getWorkerGroup() != null) { configuration.getWorkerGroup().shutdownGracefully(); } super.doStop(); } }
NettyComponent
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/Schema.java
{ "start": 11481, "end": 16151 }
enum ____ fixed, return its aliases, if any. */ public Set<String> getAliases() { throw new AvroRuntimeException("Not a named type: " + this); } /** Returns true if this record is an error type. */ public boolean isError() { throw new AvroRuntimeException("Not a record: " + this); } /** If this is an array, returns its element type. */ public Schema getElementType() { throw new AvroRuntimeException("Not an array: " + this); } /** If this is a map, returns its value type. */ public Schema getValueType() { throw new AvroRuntimeException("Not a map: " + this); } /** If this is a union, returns its types. */ public List<Schema> getTypes() { throw new AvroRuntimeException("Not a union: " + this); } /** If this is a union, return the branch with the provided full name. */ public Integer getIndexNamed(String name) { throw new AvroRuntimeException("Not a union: " + this); } /** If this is fixed, returns its size. */ public int getFixedSize() { throw new AvroRuntimeException("Not fixed: " + this); } /** * <p> * Render this as <a href="https://json.org/">JSON</a>. * </p> * * <p> * This method is equivalent to: * {@code SchemaFormatter.getInstance("json").format(this)} * </p> */ @Override public String toString() { return toString(false); } /** * Render this as <a href="https://json.org/">JSON</a>. * * @param pretty if true, pretty-print JSON. * @deprecated Use {@link SchemaFormatter#format(Schema)} instead, using the * format {@code json/pretty} or {@code json/inline} */ @Deprecated public String toString(boolean pretty) { return toString(new HashSet<String>(), pretty); } /** * Render this as <a href="https://json.org/">JSON</a>, but without inlining the * referenced schemas. * * @param referencedSchemas referenced schemas * @param pretty if true, pretty-print JSON. */ // Use at your own risk. This method should be removed with AVRO-2832. @Deprecated public String toString(Collection<Schema> referencedSchemas, boolean pretty) { Set<String> knownNames = new HashSet<>(); if (referencedSchemas != null) { for (Schema s : referencedSchemas) { knownNames.add(s.getFullName()); } } return toString(knownNames, pretty); } @Deprecated String toString(Set<String> knownNames, boolean pretty) { try { StringWriter writer = new StringWriter(); try (JsonGenerator gen = FACTORY.createGenerator(writer)) { if (pretty) gen.useDefaultPrettyPrinter(); toJson(knownNames, null, gen); gen.flush(); return writer.toString(); } } catch (IOException e) { throw new AvroRuntimeException(e); } } @Deprecated void toJson(Set<String> knownNames, String namespace, JsonGenerator gen) throws IOException { if (!hasProps()) { // no props defined gen.writeString(getName()); // just write name } else { gen.writeStartObject(); gen.writeStringField("type", getName()); writeProps(gen); gen.writeEndObject(); } } @Deprecated void fieldsToJson(Set<String> knownNames, String namespace, JsonGenerator gen) throws IOException { throw new AvroRuntimeException("Not a record: " + this); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Schema)) return false; Schema that = (Schema) o; if (!(this.type == that.type)) return false; return equalCachedHash(that) && propsEqual(that); } @Override public final int hashCode() { if (hashCode == NO_HASHCODE) hashCode = computeHash(); return hashCode; } int computeHash() { return getType().hashCode() + propsHashCode(); } final boolean equalCachedHash(Schema other) { return (hashCode == other.hashCode) || (hashCode == NO_HASHCODE) || (other.hashCode == NO_HASHCODE); } private static final Set<String> FIELD_RESERVED = Collections .unmodifiableSet(new HashSet<>(Arrays.asList("default", "doc", "name", "order", "type", "aliases"))); /** Returns true if this record is a union type. */ public boolean isUnion() { return this instanceof UnionSchema; } /** Returns true if this record is a union type containing null. */ public boolean isNullable() { if (!isUnion()) { return getType().equals(Schema.Type.NULL); } for (Schema schema : getTypes()) { if (schema.isNullable()) { return true; } } return false; } /** A field within a record. */ public static
or
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreator.java
{ "start": 850, "end": 1187 }
interface ____ a PreparedStatement given a connection, provided * by the JdbcTemplate class. Implementations are responsible for providing * SQL and any necessary parameters. * * <p>Implementations <i>do not</i> need to concern themselves with * SQLExceptions that may be thrown from operations they attempt. * The JdbcTemplate
creates
java
google__guava
android/guava/src/com/google/common/collect/FilteredSetMultimap.java
{ "start": 851, "end": 1041 }
interface ____<K extends @Nullable Object, V extends @Nullable Object> extends FilteredMultimap<K, V>, SetMultimap<K, V> { @Override SetMultimap<K, V> unfiltered(); }
FilteredSetMultimap