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
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/double2darrays/Double2DArrays_assertHasSameDimensionsAs_with_Array_Test.java
|
{
"start": 1044,
"end": 1438
}
|
class ____ extends Double2DArraysBaseTest {
@Test
void should_delegate_to_Arrays2D() {
// GIVEN
double[][] other = new double[][] { { 0.0, 4.0 }, { 8.0, 12.0 } };
// WHEN
double2dArrays.assertHasSameDimensionsAs(info, actual, other);
// THEN
verify(arrays2d).assertHasSameDimensionsAs(info, actual, other);
}
}
|
Double2DArrays_assertHasSameDimensionsAs_with_Array_Test
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleDriveEndpointBuilderFactory.java
|
{
"start": 52244,
"end": 52586
}
|
class ____ extends AbstractEndpointBuilder implements GoogleDriveEndpointBuilder, AdvancedGoogleDriveEndpointBuilder {
public GoogleDriveEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new GoogleDriveEndpointBuilderImpl(path);
}
}
|
GoogleDriveEndpointBuilderImpl
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java
|
{
"start": 2027,
"end": 2568
}
|
class ____ we're ignoring it
continue;
}
if (!pluginSwitch.isEnabled(pluginClassName)) {
continue;
}
pluginClassNames.add(pluginClassName);
} catch (Exception e) {
throw new MockitoException(
"Problems reading plugin implementation from: " + resource, e);
} finally {
IOUtil.closeQuietly(s);
}
}
return pluginClassNames;
}
}
|
name
|
java
|
apache__camel
|
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/DirectSpanDecorator.java
|
{
"start": 858,
"end": 1141
}
|
class ____ extends AbstractInternalSpanDecorator {
@Override
public String getComponent() {
return "direct";
}
@Override
public String getComponentClassName() {
return "org.apache.camel.component.direct.DirectComponent";
}
}
|
DirectSpanDecorator
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/AotInitializerNotFoundException.java
|
{
"start": 788,
"end": 1204
}
|
class ____ extends RuntimeException {
private final Class<?> mainClass;
public AotInitializerNotFoundException(Class<?> mainClass, String initializerClassName) {
super("Startup with AOT mode enabled failed: AOT initializer %s could not be found"
.formatted(initializerClassName));
this.mainClass = mainClass;
}
public Class<?> getMainClass() {
return this.mainClass;
}
}
|
AotInitializerNotFoundException
|
java
|
apache__flink
|
flink-filesystems/flink-s3-fs-presto/src/main/java/org/apache/flink/fs/s3presto/token/S3PrestoDelegationTokenProvider.java
|
{
"start": 1053,
"end": 1219
}
|
class ____ extends AbstractS3DelegationTokenProvider {
@Override
public String serviceName() {
return "s3-presto";
}
}
|
S3PrestoDelegationTokenProvider
|
java
|
hibernate__hibernate-orm
|
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/GaussDBCallableStatementSupport.java
|
{
"start": 457,
"end": 518
}
|
class ____ based on OracleCallableStatementSupport.
*/
public
|
is
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest66.java
|
{
"start": 1026,
"end": 23019
}
|
class ____ extends OracleTest {
public void test_types() throws Exception {
String sql = //
" CREATE TABLE \"SC_001\".\"TB_001\" \n" +
" (\t\"ID\" VARCHAR2(32) DEFAULT Sys_guid() NOT NULL ENABLE, \n" +
"\t\"ISDEL\" NUMBER(1,0) DEFAULT 0, \n" +
"\t\"DATAVERSION\" CHAR(14) DEFAULT to_char(sysdate,'yyyymmddhh24miss'), \n" +
"\t\"LRR_SFZH\" VARCHAR2(50), \n" +
"\t\"LRSJ\" DATE DEFAULT sysdate, \n" +
"\t\"JQZT\" VARCHAR2(10), \n" +
"\t\"JQDD\" VARCHAR2(200), \n" +
"\t\"BJFS\" VARCHAR2(10), \n" +
"\t\"BJSJ\" DATE, \n" +
"\t\"BJR\" VARCHAR2(150), \n" +
"\t\"BJDH\" VARCHAR2(50), \n" +
"\t\"BJNR\" VARCHAR2(4000), \n" +
"\t\"PDDDSJ\" DATE, \n" +
"\t\"PDJSSJ\" DATE, \n" +
"\t\"CJMJ\" VARCHAR2(50), \n" +
"\t\"CJDW\" VARCHAR2(50), \n" +
"\t\"CJSJ\" DATE, \n" +
"\t\"DDXCSJ\" DATE, \n" +
"\t\"CJCS\" VARCHAR2(2000), \n" +
"\t\"CJJG\" VARCHAR2(2000), \n" +
"\t\"GZYQ\" VARCHAR2(2000), \n" +
"\t\"JQBH\" VARCHAR2(30), \n" +
"\t\"XGR_SFZH\" VARCHAR2(50), \n" +
"\t\"XGSJ\" DATE DEFAULT sysdate, \n" +
"\t\"AJLY\" VARCHAR2(10) DEFAULT '03', \n" +
"\t\"JQMC\" VARCHAR2(200), \n" +
"\t\"CJJGSM\" VARCHAR2(2000), \n" +
"\t\"CJMJ_XM\" VARCHAR2(200), \n" +
"\t\"CJDW_MC\" VARCHAR2(200), \n" +
"\t\"JQLB\" VARCHAR2(20), \n" +
"\t\"XXLX\" VARCHAR2(20), \n" +
"\t\"JJDBH\" VARCHAR2(50), \n" +
"\t\"XZQH\" VARCHAR2(50), \n" +
"\t\"CBQY_BH\" VARCHAR2(50), \n" +
"\t\"SJLY\" VARCHAR2(200) DEFAULT '????', \n" +
"\t\"GXDWDM\" VARCHAR2(20), \n" +
"\t\"BJLXDM\" VARCHAR2(20), \n" +
"\t\"BJXLDM\" VARCHAR2(20), \n" +
"\t\"CJDW_OLD\" VARCHAR2(50), \n" +
"\t\"JQLY\" VARCHAR2(20), \n" +
"\t\"IS_AJ_ANALYZE\" VARCHAR2(1) DEFAULT '9', \n" +
"\t\"SJJE\" VARCHAR2(20), \n" +
"\t\"YSDWFL\" VARCHAR2(5), \n" +
"\t\"YSDWMC\" VARCHAR2(50), \n" +
"\t\"YSDWCBR\" VARCHAR2(20), \n" +
"\t\"CBRLXDH\" VARCHAR2(20), \n" +
"\t\"TBDW\" VARCHAR2(50), \n" +
"\t\"TBR\" VARCHAR2(20), \n" +
"\t\"TBRQ\" DATE, \n" +
"\t\"JZ_JQLB\" VARCHAR2(20), \n" +
"\t\"SFZR\" VARCHAR2(10), \n" +
"\t\"SJDWDM\" VARCHAR2(40), \n" +
"\t CONSTRAINT \"PK_CASE_GG_JQXX1\" PRIMARY KEY (\"ID\")\n" +
" USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS \n" +
" STORAGE(INITIAL 150994944 NEXT 8388608 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_IDX\" ENABLE\n" +
" ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" STORAGE(\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" \n" +
" PARTITION BY RANGE (\"LRSJ\") \n" +
" (PARTITION \"T_RANGE_V1\" VALUES LESS THAN (TO_DATE(' 2015-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"T_RANGE_V2\" VALUES LESS THAN (TO_DATE(' 2015-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"T_RANGE_V3\" VALUES LESS THAN (TO_DATE(' 2016-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"T_RANGE_V4\" VALUES LESS THAN (TO_DATE(' 2016-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"T_RANGE_V5\" VALUES LESS THAN (TO_DATE(' 2017-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"T_RANGE_V6\" VALUES LESS THAN (TO_DATE(' 2017-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 80 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 553648128 NEXT 16384 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" , \n" +
" PARTITION \"MAXPART\" VALUES LESS THAN (MAXVALUE) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" +
" COMPRESS FOR OLTP LOGGING \n" +
" STORAGE(INITIAL 8388608 NEXT 8388608 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" +
" BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"RDP_DATA\" ) ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE \"SC_001\".\"TB_001\" (\n" +
"\t\"ID\" VARCHAR2(32) DEFAULT Sys_guid() NOT NULL ENABLE,\n" +
"\t\"ISDEL\" NUMBER(1, 0) DEFAULT 0,\n" +
"\t\"DATAVERSION\" CHAR(14) DEFAULT to_char(SYSDATE, 'yyyymmddhh24miss'),\n" +
"\t\"LRR_SFZH\" VARCHAR2(50),\n" +
"\t\"LRSJ\" DATE DEFAULT SYSDATE,\n" +
"\t\"JQZT\" VARCHAR2(10),\n" +
"\t\"JQDD\" VARCHAR2(200),\n" +
"\t\"BJFS\" VARCHAR2(10),\n" +
"\t\"BJSJ\" DATE,\n" +
"\t\"BJR\" VARCHAR2(150),\n" +
"\t\"BJDH\" VARCHAR2(50),\n" +
"\t\"BJNR\" VARCHAR2(4000),\n" +
"\t\"PDDDSJ\" DATE,\n" +
"\t\"PDJSSJ\" DATE,\n" +
"\t\"CJMJ\" VARCHAR2(50),\n" +
"\t\"CJDW\" VARCHAR2(50),\n" +
"\t\"CJSJ\" DATE,\n" +
"\t\"DDXCSJ\" DATE,\n" +
"\t\"CJCS\" VARCHAR2(2000),\n" +
"\t\"CJJG\" VARCHAR2(2000),\n" +
"\t\"GZYQ\" VARCHAR2(2000),\n" +
"\t\"JQBH\" VARCHAR2(30),\n" +
"\t\"XGR_SFZH\" VARCHAR2(50),\n" +
"\t\"XGSJ\" DATE DEFAULT SYSDATE,\n" +
"\t\"AJLY\" VARCHAR2(10) DEFAULT '03',\n" +
"\t\"JQMC\" VARCHAR2(200),\n" +
"\t\"CJJGSM\" VARCHAR2(2000),\n" +
"\t\"CJMJ_XM\" VARCHAR2(200),\n" +
"\t\"CJDW_MC\" VARCHAR2(200),\n" +
"\t\"JQLB\" VARCHAR2(20),\n" +
"\t\"XXLX\" VARCHAR2(20),\n" +
"\t\"JJDBH\" VARCHAR2(50),\n" +
"\t\"XZQH\" VARCHAR2(50),\n" +
"\t\"CBQY_BH\" VARCHAR2(50),\n" +
"\t\"SJLY\" VARCHAR2(200) DEFAULT '????',\n" +
"\t\"GXDWDM\" VARCHAR2(20),\n" +
"\t\"BJLXDM\" VARCHAR2(20),\n" +
"\t\"BJXLDM\" VARCHAR2(20),\n" +
"\t\"CJDW_OLD\" VARCHAR2(50),\n" +
"\t\"JQLY\" VARCHAR2(20),\n" +
"\t\"IS_AJ_ANALYZE\" VARCHAR2(1) DEFAULT '9',\n" +
"\t\"SJJE\" VARCHAR2(20),\n" +
"\t\"YSDWFL\" VARCHAR2(5),\n" +
"\t\"YSDWMC\" VARCHAR2(50),\n" +
"\t\"YSDWCBR\" VARCHAR2(20),\n" +
"\t\"CBRLXDH\" VARCHAR2(20),\n" +
"\t\"TBDW\" VARCHAR2(50),\n" +
"\t\"TBR\" VARCHAR2(20),\n" +
"\t\"TBRQ\" DATE,\n" +
"\t\"JZ_JQLB\" VARCHAR2(20),\n" +
"\t\"SFZR\" VARCHAR2(10),\n" +
"\t\"SJDWDM\" VARCHAR2(40),\n" +
"\tCONSTRAINT \"PK_CASE_GG_JQXX1\" PRIMARY KEY (\"ID\")\n" +
"\t\tUSING INDEX\n" +
"\t\tPCTFREE 10\n" +
"\t\tINITRANS 2\n" +
"\t\tMAXTRANS 255\n" +
"\t\tTABLESPACE \"RDP_IDX\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 150994944\n" +
"\t\t\tNEXT 8388608\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t)\n" +
"\t\tCOMPUTE STATISTICS\n" +
"\t\tENABLE\n" +
")\n" +
"PCTFREE 10\n" +
"PCTUSED 40\n" +
"INITRANS 1\n" +
"MAXTRANS 255\n" +
"TABLESPACE \"RDP_DATA\"\n" +
"STORAGE (\n" +
"\tBUFFER_POOL DEFAULT\n" +
"\tFLASH_CACHE DEFAULT\n" +
"\tCELL_FLASH_CACHE DEFAULT\n" +
")\n" +
"PARTITION BY RANGE (\"LRSJ\") (\n" +
"\tPARTITION \"T_RANGE_V1\" VALUES LESS THAN (TO_DATE(' 2015-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"T_RANGE_V2\" VALUES LESS THAN (TO_DATE(' 2015-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"T_RANGE_V3\" VALUES LESS THAN (TO_DATE(' 2016-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"T_RANGE_V4\" VALUES LESS THAN (TO_DATE(' 2016-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"T_RANGE_V5\" VALUES LESS THAN (TO_DATE(' 2017-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"T_RANGE_V6\" VALUES LESS THAN (TO_DATE(' 2017-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))\n" +
"\t\tPCTFREE 80\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 553648128\n" +
"\t\t\tNEXT 16384\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t),\n" +
"\tPARTITION \"MAXPART\" VALUES LESS THAN (MAXVALUE)\n" +
"\t\tPCTFREE 10\n" +
"\t\tPCTUSED 40\n" +
"\t\tINITRANS 1\n" +
"\t\tMAXTRANS 255\n" +
"\t\tCOMPRESS\n" +
"\t\tLOGGING\n" +
"\t\tTABLESPACE \"RDP_DATA\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 8388608\n" +
"\t\t\tNEXT 8388608\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t\tFLASH_CACHE DEFAULT\n" +
"\t\t\tCELL_FLASH_CACHE DEFAULT\n" +
"\t\t)\n" +
")",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
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(1, visitor.getTables().size());
assertEquals(52, visitor.getColumns().size());
assertTrue(visitor.containsColumn("SC_001.TB_001", "ID"));
}
}
|
OracleCreateTableTest66
|
java
|
apache__camel
|
components/camel-shiro/src/test/java/org/apache/camel/component/shiro/security/ShiroAuthorizationTest.java
|
{
"start": 1333,
"end": 9096
}
|
class ____ extends CamelTestSupport {
@EndpointInject("mock:success")
protected MockEndpoint successEndpoint;
@EndpointInject("mock:authorizationException")
protected MockEndpoint failureEndpoint;
private byte[] passPhrase = {
(byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B,
(byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13,
(byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17 };
@Test
public void testShiroAuthorizationFailure() throws Exception {
// The user ringo has role sec-level1 with permission set as zone1:readonly:*
// Since the required permission is zone1:readwrite:*, this request should fail authorization
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("ringo", "starr");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(0);
failureEndpoint.expectedMessageCount(1);
template.send("direct:secureEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Test
public void testSuccessfulAuthorization() throws Exception {
// The user george has role sec-level2 with permission set as zone1:*
// Since the required permission incorporates zone1:readwrite:*, this request should successfully pass authorization
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("george", "harrison");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(1);
failureEndpoint.expectedMessageCount(0);
template.send("direct:secureEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Test
public void testSuccessfulAuthorizationForHigherScope() throws Exception {
// The user john has role sec-level3 with permission set as *
// Since the required permission incorporates zone1:readwrite:*, this request should successfully pass authorization
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("paul", "mccartney");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(1);
failureEndpoint.expectedMessageCount(0);
template.send("direct:secureEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Test
public void testSuccessfulAuthorizationAny() throws Exception {
// The user ringo has role sec-level1 with permission set as zone1:readonly:*
// This permission is allowed and so this should work
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("ringo", "starr");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(1);
failureEndpoint.expectedMessageCount(0);
template.send("direct:secureAnyEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Test
public void testFailureAuthorizationAll() throws Exception {
// The user ringo has role sec-level1 with permission set as zone1:readonly:*
// However, ringo does not have a permission of "zone1:writeonly:*" and so authorization fails
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("ringo", "starr");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(0);
failureEndpoint.expectedMessageCount(1);
template.send("direct:secureAllEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Test
public void testSuccessfulAuthorizationAll() throws Exception {
// The user george has role sec-level2 with permission set as zone1:*
// Since the required permission incorporates all permissions, this request should successfully pass authorization
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken("george", "harrison");
TestShiroSecurityTokenInjector shiroSecurityTokenInjector
= new TestShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
successEndpoint.expectedMessageCount(1);
failureEndpoint.expectedMessageCount(0);
template.send("direct:secureAllEndpoint", shiroSecurityTokenInjector);
successEndpoint.assertIsSatisfied();
failureEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder[] createRouteBuilders() {
return new RouteBuilder[] { new RouteBuilder() {
public void configure() {
List<Permission> permissionsList = new ArrayList<>();
Permission permission = new WildcardPermission("zone1:readwrite:*");
permissionsList.add(permission);
final ShiroSecurityPolicy securityPolicy
= new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
onException(CamelAuthorizationException.class).to("mock:authorizationException");
from("direct:secureEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
}
}, new RouteBuilder() {
public void configure() {
List<Permission> permissionsList = new ArrayList<>();
Permission permission = new WildcardPermission("zone1:readonly:*");
permissionsList.add(permission);
permission = new WildcardPermission("zone1:writeonly:*");
permissionsList.add(permission);
final ShiroSecurityPolicy securityPolicy
= new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
onException(CamelAuthorizationException.class).to("mock:authorizationException");
from("direct:secureAnyEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
}
}, new RouteBuilder() {
public void configure() {
List<Permission> permissionsList = new ArrayList<>();
Permission permission = new WildcardPermission("zone1:readonly:*");
permissionsList.add(permission);
permission = new WildcardPermission("zone1:writeonly:*");
permissionsList.add(permission);
final ShiroSecurityPolicy securityPolicy
= new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase, true, permissionsList);
securityPolicy.setAllPermissionsRequired(true);
onException(CamelAuthorizationException.class).to("mock:authorizationException");
from("direct:secureAllEndpoint").policy(securityPolicy).to("log:incoming payload").to("mock:success");
}
}
};
}
private static
|
ShiroAuthorizationTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jackson/src/main/java/org/springframework/boot/jackson/autoconfigure/JacksonAutoConfiguration.java
|
{
"start": 12132,
"end": 15014
}
|
class ____<B extends MapperBuilder<?, ?>> implements Ordered {
private final JacksonProperties jacksonProperties;
private final Collection<JacksonModule> modules;
AbstractMapperBuilderCustomizer(JacksonProperties jacksonProperties, Collection<JacksonModule> modules) {
this.jacksonProperties = jacksonProperties;
this.modules = modules;
}
@Override
public int getOrder() {
return 0;
}
protected JacksonProperties properties() {
return this.jacksonProperties;
}
protected void customize(B builder) {
if (this.jacksonProperties.isUseJackson2Defaults()) {
builder.configureForJackson2()
.disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS);
}
if (this.jacksonProperties.isFindAndAddModules()) {
builder.findAndAddModules(getClass().getClassLoader());
}
if (this.jacksonProperties.getDefaultPropertyInclusion() != null) {
builder.changeDefaultPropertyInclusion(
(handler) -> handler.withValueInclusion(this.jacksonProperties.getDefaultPropertyInclusion()));
}
if (this.jacksonProperties.getTimeZone() != null) {
builder.defaultTimeZone(this.jacksonProperties.getTimeZone());
}
configureVisibility(builder, this.jacksonProperties.getVisibility());
configureFeatures(builder, this.jacksonProperties.getDeserialization(), builder::configure);
configureFeatures(builder, this.jacksonProperties.getSerialization(), builder::configure);
configureFeatures(builder, this.jacksonProperties.getMapper(), builder::configure);
configureFeatures(builder, this.jacksonProperties.getDatatype().getDatetime(), builder::configure);
configureFeatures(builder, this.jacksonProperties.getDatatype().getEnum(), builder::configure);
configureFeatures(builder, this.jacksonProperties.getDatatype().getJsonNode(), builder::configure);
configureDateFormat(builder);
configurePropertyNamingStrategy(builder);
configureModules(builder);
configureLocale(builder);
configureDefaultLeniency(builder);
configureConstructorDetector(builder);
}
protected <T> void configureFeatures(B builder, Map<T, Boolean> features, BiConsumer<T, Boolean> configure) {
features.forEach((feature, value) -> {
if (value != null) {
configure.accept(feature, value);
}
});
}
private void configureVisibility(MapperBuilder<?, ?> builder,
Map<PropertyAccessor, JsonAutoDetect.Visibility> visibilities) {
builder.changeDefaultVisibility((visibilityChecker) -> {
for (Map.Entry<PropertyAccessor, JsonAutoDetect.Visibility> entry : visibilities.entrySet()) {
visibilityChecker = visibilityChecker.withVisibility(entry.getKey(), entry.getValue());
}
return visibilityChecker;
});
}
private void configureDateFormat(MapperBuilder<?, ?> builder) {
// We support a fully qualified
|
AbstractMapperBuilderCustomizer
|
java
|
google__guice
|
examples/guice-demo/src/test/java/com/example/AppTest.java
|
{
"start": 479,
"end": 1097
}
|
class ____ {
private final List<String> messages = new ArrayList<>();
@Bind @App.Message private final String message = "hello, test";
@Bind
private final Printer printer =
new Printer() {
@Override
public void printMessage(String message) {
messages.add(message);
}
};
@Inject private App app;
@Before
public void setUp() {
Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
}
@Test
public void run_printsMessage() {
app.run();
assertEquals(1, messages.size());
assertEquals(message, messages.get(0));
}
}
|
AppTest
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/comparable/AbstractComparableAssert_isGreaterThanOrEqualTo_Test.java
|
{
"start": 1001,
"end": 1391
}
|
class ____ extends AbstractComparableAssertBaseTest {
@Override
protected ConcreteComparableAssert invoke_api_method() {
return assertions.isGreaterThanOrEqualTo(6);
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions), 6);
}
}
|
AbstractComparableAssert_isGreaterThanOrEqualTo_Test
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/collections/mappedsuperclasselement/MappedSuperclassComponentSetTestEntity.java
|
{
"start": 711,
"end": 2455
}
|
class ____ {
@Id
@GeneratedValue
private Integer id;
@ElementCollection
@CollectionTable(name = "MCompTestEntityComps", joinColumns = @JoinColumn(name = "entity_id"))
private Set<Code> comps = new HashSet<Code>();
@NotAudited
@ElementCollection
@CollectionTable(name = "MCompTestEntityCompsNotAudited", joinColumns = @JoinColumn(name = "entity_id"))
private Set<Code> compsNotAudited = new HashSet<Code>();
public MappedSuperclassComponentSetTestEntity() {
}
public MappedSuperclassComponentSetTestEntity(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<Code> getComps() {
return comps;
}
public void setComps(Set<Code> comps) {
this.comps = comps;
}
public Set<Code> getCompsNotAudited() {
return compsNotAudited;
}
public void setCompsNotAudited(Set<Code> comps) {
this.compsNotAudited = compsNotAudited;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof MappedSuperclassComponentSetTestEntity ) ) {
return false;
}
MappedSuperclassComponentSetTestEntity that = (MappedSuperclassComponentSetTestEntity) o;
if ( comps != null ? !comps.equals( that.comps ) : that.comps != null ) {
return false;
}
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (comps != null ? comps.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ComponentSetTestEntity{" +
"id=" + id +
", comps=" + comps +
'}';
}
}
|
MappedSuperclassComponentSetTestEntity
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/EmbeddableWithParentWithInheritance2Test.java
|
{
"start": 2409,
"end": 2716
}
|
class ____ {
Long id;
public Food() {
}
public String describe() {
return "Good food";
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@Entity(name = "Roquefort")
@DiscriminatorValue("ROQUEFORT")
public static
|
Food
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/EhcacheComponentBuilderFactory.java
|
{
"start": 1371,
"end": 1834
}
|
interface ____ {
/**
* Ehcache (camel-ehcache)
* Perform caching operations using Ehcache.
*
* Category: cache,clustering
* Since: 2.18
* Maven coordinates: org.apache.camel:camel-ehcache
*
* @return the dsl builder
*/
static EhcacheComponentBuilder ehcache() {
return new EhcacheComponentBuilderImpl();
}
/**
* Builder for the Ehcache component.
*/
|
EhcacheComponentBuilderFactory
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/InstanceOfAssertFactories.java
|
{
"start": 3395,
"end": 48448
}
|
interface ____ {
/**
* {@link InstanceOfAssertFactory} for a {@link Predicate}, assuming {@code Object} as input type.
*
* @see #predicate(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Predicate, PredicateAssert<Object>> PREDICATE = predicate(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Predicate}.
*
* @param <T> the {@code Predicate} input type.
* @param type the input type instance.
* @return the factory instance.
*
* @see #PREDICATE
*/
@SuppressWarnings("rawtypes")
static <T> InstanceOfAssertFactory<Predicate, PredicateAssert<T>> predicate(Class<T> type) {
return new InstanceOfAssertFactory<>(Predicate.class, new Class[] { type }, Assertions::<T> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link IntPredicate}.
*/
InstanceOfAssertFactory<IntPredicate, IntPredicateAssert> INT_PREDICATE = new InstanceOfAssertFactory<>(IntPredicate.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link LongPredicate}.
*/
InstanceOfAssertFactory<LongPredicate, LongPredicateAssert> LONG_PREDICATE = new InstanceOfAssertFactory<>(LongPredicate.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link DoublePredicate}.
*/
InstanceOfAssertFactory<DoublePredicate, DoublePredicateAssert> DOUBLE_PREDICATE = new InstanceOfAssertFactory<>(DoublePredicate.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link CompletableFuture}, assuming {@code Object} as result type.
*
* @see #completableFuture(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<CompletableFuture, CompletableFutureAssert<Object>> COMPLETABLE_FUTURE = completableFuture(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link CompletableFuture}.
*
* @param <RESULT> the {@code CompletableFuture} result type.
* @param resultType the result type instance.
* @return the factory instance.
*
* @see #COMPLETABLE_FUTURE
*/
@SuppressWarnings("rawtypes")
static <RESULT> InstanceOfAssertFactory<CompletableFuture, CompletableFutureAssert<RESULT>> completableFuture(Class<RESULT> resultType) {
return new InstanceOfAssertFactory<>(CompletableFuture.class, new Class[] { resultType }, Assertions::<RESULT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link CompletionStage}, assuming {@code Object} as result type.
*
* @see #completionStage(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<CompletionStage, CompletableFutureAssert<Object>> COMPLETION_STAGE = completionStage(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link CompletionStage}.
*
* @param <RESULT> the {@code CompletionStage} result type.
* @param resultType the result type instance.
* @return the factory instance.
*
* @see #COMPLETION_STAGE
*/
@SuppressWarnings("rawtypes")
static <RESULT> InstanceOfAssertFactory<CompletionStage, CompletableFutureAssert<RESULT>> completionStage(Class<RESULT> resultType) {
return new InstanceOfAssertFactory<>(CompletionStage.class, new Class[] { resultType }, Assertions::<RESULT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link Optional}, assuming {@code Object} as value type.
*
* @see #optional(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Optional, OptionalAssert<Object>> OPTIONAL = optional(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link Optional}.
*
* @param <VALUE> the {@code Optional} value type.
* @param resultType the value type instance.
* @return the factory instance.
*
* @see #OPTIONAL
*/
@SuppressWarnings("rawtypes")
static <VALUE> InstanceOfAssertFactory<Optional, OptionalAssert<VALUE>> optional(Class<VALUE> resultType) {
return new InstanceOfAssertFactory<>(Optional.class, new Class[] { resultType }, Assertions::<VALUE> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link OptionalDouble}.
*/
InstanceOfAssertFactory<OptionalDouble, OptionalDoubleAssert> OPTIONAL_DOUBLE = new InstanceOfAssertFactory<>(OptionalDouble.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link OptionalInt}.
*/
InstanceOfAssertFactory<OptionalInt, OptionalIntAssert> OPTIONAL_INT = new InstanceOfAssertFactory<>(OptionalInt.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link OptionalLong}.
*/
InstanceOfAssertFactory<OptionalLong, OptionalLongAssert> OPTIONAL_LONG = new InstanceOfAssertFactory<>(OptionalLong.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link Matcher}.
*/
InstanceOfAssertFactory<Matcher, MatcherAssert> MATCHER = new InstanceOfAssertFactory<>(Matcher.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link BigDecimal}.
*/
InstanceOfAssertFactory<BigDecimal, AbstractBigDecimalAssert<?>> BIG_DECIMAL = new InstanceOfAssertFactory<>(BigDecimal.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link BigInteger}.
*/
InstanceOfAssertFactory<BigInteger, AbstractBigIntegerAssert<?>> BIG_INTEGER = new InstanceOfAssertFactory<>(BigInteger.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link URI}.
* <p>
* Note: The {@code TYPE} suffix prevents the shadowing of {@code java.net.URI} when the factory is statically imported.
* </p>
*
* @since 3.13.2
*/
InstanceOfAssertFactory<URI, AbstractUriAssert<?>> URI_TYPE = new InstanceOfAssertFactory<>(URI.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link URL}.
* <p>
* Note: The {@code TYPE} suffix prevents the shadowing of {@code java.net.URL} when the factory is statically imported.
* </p>
*
* @since 3.13.2
*/
InstanceOfAssertFactory<URL, AbstractUrlAssert<?>> URL_TYPE = new InstanceOfAssertFactory<>(URL.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code boolean} or its corresponding boxed type {@link Boolean}.
*/
InstanceOfAssertFactory<Boolean, AbstractBooleanAssert<?>> BOOLEAN = new InstanceOfAssertFactory<>(Boolean.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code boolean} array.
*/
InstanceOfAssertFactory<boolean[], AbstractBooleanArrayAssert<?>> BOOLEAN_ARRAY = new InstanceOfAssertFactory<>(boolean[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code boolean} two-dimensional array.
*/
InstanceOfAssertFactory<boolean[][], Boolean2DArrayAssert> BOOLEAN_2D_ARRAY = new InstanceOfAssertFactory<>(boolean[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code byte} or its corresponding boxed type {@link Byte}.
*/
InstanceOfAssertFactory<Byte, AbstractByteAssert<?>> BYTE = new InstanceOfAssertFactory<>(Byte.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code byte} array.
*/
InstanceOfAssertFactory<byte[], AbstractByteArrayAssert<?>> BYTE_ARRAY = new InstanceOfAssertFactory<>(byte[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code byte} two-dimensional array.
*/
InstanceOfAssertFactory<byte[][], Byte2DArrayAssert> BYTE_2D_ARRAY = new InstanceOfAssertFactory<>(byte[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code char} or its corresponding boxed type {@link Character}.
*/
InstanceOfAssertFactory<Character, AbstractCharacterAssert<?>> CHARACTER = new InstanceOfAssertFactory<>(Character.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code char} array.
*/
InstanceOfAssertFactory<char[], AbstractCharArrayAssert<?>> CHAR_ARRAY = new InstanceOfAssertFactory<>(char[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code char} two-dimensional array.
*/
InstanceOfAssertFactory<char[][], Char2DArrayAssert> CHAR_2D_ARRAY = new InstanceOfAssertFactory<>(char[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Class}.
*/
@SuppressWarnings("rawtypes") // using Class instance
InstanceOfAssertFactory<Class, ClassAssert> CLASS = new InstanceOfAssertFactory<>(Class.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code double} or its corresponding boxed type {@link Double}.
*/
InstanceOfAssertFactory<Double, AbstractDoubleAssert<?>> DOUBLE = new InstanceOfAssertFactory<>(Double.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code double} array.
*/
InstanceOfAssertFactory<double[], AbstractDoubleArrayAssert<?>> DOUBLE_ARRAY = new InstanceOfAssertFactory<>(double[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code double} two-dimensional array.
*/
InstanceOfAssertFactory<double[][], Double2DArrayAssert> DOUBLE_2D_ARRAY = new InstanceOfAssertFactory<>(double[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link File}.
*/
InstanceOfAssertFactory<File, AbstractFileAssert<?>> FILE = new InstanceOfAssertFactory<>(File.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Future}, assuming {@code Object} as result type.
*
* @see #future(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Future, FutureAssert<Object>> FUTURE = future(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Future}.
*
* @param <RESULT> the {@code Future} result type.
* @param resultType the result type instance.
* @return the factory instance.
*
* @see #FUTURE
*/
@SuppressWarnings("rawtypes")
static <RESULT> InstanceOfAssertFactory<Future, FutureAssert<RESULT>> future(Class<RESULT> resultType) {
return new InstanceOfAssertFactory<>(Future.class, new Class[] { resultType }, Assertions::<RESULT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link InputStream}.
*/
InstanceOfAssertFactory<InputStream, AbstractInputStreamAssert<?, ?>> INPUT_STREAM = new InstanceOfAssertFactory<>(InputStream.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code float} or its corresponding boxed type {@link Float}.
*/
InstanceOfAssertFactory<Float, AbstractFloatAssert<?>> FLOAT = new InstanceOfAssertFactory<>(Float.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code float} array.
*/
InstanceOfAssertFactory<float[], AbstractFloatArrayAssert<?>> FLOAT_ARRAY = new InstanceOfAssertFactory<>(float[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code float} two-dimensional array.
*/
InstanceOfAssertFactory<float[][], Float2DArrayAssert> FLOAT_2D_ARRAY = new InstanceOfAssertFactory<>(float[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@code integer} or its corresponding boxed type {@link Integer}.
*/
InstanceOfAssertFactory<Integer, AbstractIntegerAssert<?>> INTEGER = new InstanceOfAssertFactory<>(Integer.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@code int} array.
*/
InstanceOfAssertFactory<int[], AbstractIntArrayAssert<?>> INT_ARRAY = new InstanceOfAssertFactory<>(int[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@code int} two-dimensional array.
*/
InstanceOfAssertFactory<int[][], Int2DArrayAssert> INT_2D_ARRAY = new InstanceOfAssertFactory<>(int[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code long} or its corresponding boxed type {@link Long}.
*/
InstanceOfAssertFactory<Long, AbstractLongAssert<?>> LONG = new InstanceOfAssertFactory<>(Long.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code long} array.
*/
InstanceOfAssertFactory<long[], AbstractLongArrayAssert<?>> LONG_ARRAY = new InstanceOfAssertFactory<>(long[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code long} two-dimensional array.
*/
InstanceOfAssertFactory<long[][], Long2DArrayAssert> LONG_2D_ARRAY = new InstanceOfAssertFactory<>(long[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an object of a specific type.
* <p>
* <b>While this factory ensures that {@code actual} is an instance of the input type, it creates always
* an {@link ObjectAssert} with the corresponding type.</b>
*
* @param <T> the object type.
* @param type the object type instance.
* @return the factory instance.
*/
static <T> InstanceOfAssertFactory<T, ObjectAssert<T>> type(Class<T> type) {
return new InstanceOfAssertFactory<>(type, Assertions::assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an array of {@link Object}.
*
* @see #array(Class)
*/
InstanceOfAssertFactory<Object[], ObjectArrayAssert<Object>> ARRAY = array(Object.class);
/**
* {@link InstanceOfAssertFactory} for an array of elements.
*
* @param <COMPONENT> the component type.
* @param componentType the component type instance.
* @return the factory instance.
*
* @see #ARRAY
*/
static <COMPONENT> InstanceOfAssertFactory<COMPONENT[], ObjectArrayAssert<COMPONENT>> array(Class<COMPONENT> componentType) {
@SuppressWarnings("unchecked")
Class<COMPONENT[]> arrayType = (Class<COMPONENT[]>) Array.newInstance(componentType, 0).getClass();
return new InstanceOfAssertFactory<>(arrayType, Assertions::assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a two-dimensional array of {@link Object}.
*
* @see #array(Class)
*/
InstanceOfAssertFactory<Object[][], Object2DArrayAssert<Object>> ARRAY_2D = array2D(Object.class);
/**
* {@link InstanceOfAssertFactory} for a two-dimensional array of elements.
*
* @param <COMPONENT> the component type.
* @param componentType the component type instance.
* @return the factory instance.
*
* @see #ARRAY
*/
static <COMPONENT> InstanceOfAssertFactory<COMPONENT[][], Object2DArrayAssert<COMPONENT>> array2D(Class<COMPONENT> componentType) {
@SuppressWarnings("unchecked")
Class<COMPONENT[][]> arrayType = (Class<COMPONENT[][]>) Array.newInstance(componentType, 0, 0).getClass();
return new InstanceOfAssertFactory<>(arrayType, Assertions::assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@code short} or its corresponding boxed type {@link Short}.
*/
InstanceOfAssertFactory<Short, AbstractShortAssert<?>> SHORT = new InstanceOfAssertFactory<>(Short.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code short} array.
*/
InstanceOfAssertFactory<short[], AbstractShortArrayAssert<?>> SHORT_ARRAY = new InstanceOfAssertFactory<>(short[].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@code short} two-dimensional array.
*/
InstanceOfAssertFactory<short[][], Short2DArrayAssert> SHORT_2D_ARRAY = new InstanceOfAssertFactory<>(short[][].class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Date}.
*/
InstanceOfAssertFactory<Date, AbstractDateAssert<?>> DATE = new InstanceOfAssertFactory<>(Date.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Temporal}.
*
* @since 3.26.0
*/
InstanceOfAssertFactory<Temporal, TemporalAssert> TEMPORAL = new InstanceOfAssertFactory<>(Temporal.class,
Assertions::assertThatTemporal);
/**
* {@link InstanceOfAssertFactory} for a {@link ZonedDateTime}.
*/
InstanceOfAssertFactory<ZonedDateTime, AbstractZonedDateTimeAssert<?>> ZONED_DATE_TIME = new InstanceOfAssertFactory<>(ZonedDateTime.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link LocalDateTime}.
*/
InstanceOfAssertFactory<LocalDateTime, AbstractLocalDateTimeAssert<?>> LOCAL_DATE_TIME = new InstanceOfAssertFactory<>(LocalDateTime.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link OffsetDateTime}.
*/
InstanceOfAssertFactory<OffsetDateTime, AbstractOffsetDateTimeAssert<?>> OFFSET_DATE_TIME = new InstanceOfAssertFactory<>(OffsetDateTime.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link OffsetTime}.
*/
InstanceOfAssertFactory<OffsetTime, AbstractOffsetTimeAssert<?>> OFFSET_TIME = new InstanceOfAssertFactory<>(OffsetTime.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link LocalTime}.
*/
InstanceOfAssertFactory<LocalTime, AbstractLocalTimeAssert<?>> LOCAL_TIME = new InstanceOfAssertFactory<>(LocalTime.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link LocalDate}.
*/
InstanceOfAssertFactory<LocalDate, AbstractLocalDateAssert<?>> LOCAL_DATE = new InstanceOfAssertFactory<>(LocalDate.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link YearMonth}.
*
* @since 3.26.0
*/
InstanceOfAssertFactory<YearMonth, AbstractYearMonthAssert<?>> YEAR_MONTH = new InstanceOfAssertFactory<>(YearMonth.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link Instant}.
*/
InstanceOfAssertFactory<Instant, AbstractInstantAssert<?>> INSTANT = new InstanceOfAssertFactory<>(Instant.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Duration}.
*
* @since 3.15.0
*/
InstanceOfAssertFactory<Duration, AbstractDurationAssert<?>> DURATION = new InstanceOfAssertFactory<>(Duration.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Period}.
*
* @since 3.17.0
*/
InstanceOfAssertFactory<Period, AbstractPeriodAssert<?>> PERIOD = new InstanceOfAssertFactory<>(Period.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicBoolean}.
*/
InstanceOfAssertFactory<AtomicBoolean, AtomicBooleanAssert> ATOMIC_BOOLEAN = new InstanceOfAssertFactory<>(AtomicBoolean.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicInteger}.
*/
InstanceOfAssertFactory<AtomicInteger, AtomicIntegerAssert> ATOMIC_INTEGER = new InstanceOfAssertFactory<>(AtomicInteger.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicIntegerArray}.
*/
InstanceOfAssertFactory<AtomicIntegerArray, AtomicIntegerArrayAssert> ATOMIC_INTEGER_ARRAY = new InstanceOfAssertFactory<>(AtomicIntegerArray.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicIntegerFieldUpdater}, assuming {@code Object} as object type.
*
* @see #atomicIntegerFieldUpdater(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicIntegerFieldUpdater, AtomicIntegerFieldUpdaterAssert<Object>> ATOMIC_INTEGER_FIELD_UPDATER = atomicIntegerFieldUpdater(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicIntegerFieldUpdater}.
*
* @param <T> the {@code AtomicIntegerFieldUpdater} object type.
* @param objectType the object type instance.
* @return the factory instance.
*
* @see #ATOMIC_INTEGER_FIELD_UPDATER
*/
@SuppressWarnings("rawtypes")
static <T> InstanceOfAssertFactory<AtomicIntegerFieldUpdater, AtomicIntegerFieldUpdaterAssert<T>> atomicIntegerFieldUpdater(Class<T> objectType) {
return new InstanceOfAssertFactory<>(AtomicIntegerFieldUpdater.class, new Class[] { objectType }, Assertions::<T> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link LongAdder}.
*/
InstanceOfAssertFactory<LongAdder, LongAdderAssert> LONG_ADDER = new InstanceOfAssertFactory<>(LongAdder.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicLong}.
*/
InstanceOfAssertFactory<AtomicLong, AtomicLongAssert> ATOMIC_LONG = new InstanceOfAssertFactory<>(AtomicLong.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicLongArray}.
*/
InstanceOfAssertFactory<AtomicLongArray, AtomicLongArrayAssert> ATOMIC_LONG_ARRAY = new InstanceOfAssertFactory<>(AtomicLongArray.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicLongFieldUpdater}, assuming {@code Object} as object type.
*
* @see #atomicLongFieldUpdater(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicLongFieldUpdater, AtomicLongFieldUpdaterAssert<Object>> ATOMIC_LONG_FIELD_UPDATER = atomicLongFieldUpdater(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicIntegerFieldUpdater}.
*
* @param <T> the {@code AtomicLongFieldUpdater} object type.
* @param objectType the object type instance.
* @return the factory instance.
*
* @see #ATOMIC_LONG_FIELD_UPDATER
*/
@SuppressWarnings("rawtypes")
static <T> InstanceOfAssertFactory<AtomicLongFieldUpdater, AtomicLongFieldUpdaterAssert<T>> atomicLongFieldUpdater(Class<T> objectType) {
return new InstanceOfAssertFactory<>(AtomicLongFieldUpdater.class, new Class[] { objectType }, Assertions::<T> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReference}, assuming {@code Object} as value type.
*
* @see #atomicReference(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicReference, AtomicReferenceAssert<Object>> ATOMIC_REFERENCE = atomicReference(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReference}.
*
* @param <V> the {@code AtomicReference} value type.
* @param valueType the value type instance.
* @return the factory instance.
*
* @see #ATOMIC_REFERENCE
*/
@SuppressWarnings("rawtypes")
static <V> InstanceOfAssertFactory<AtomicReference, AtomicReferenceAssert<V>> atomicReference(Class<V> valueType) {
return new InstanceOfAssertFactory<>(AtomicReference.class, new Class[] { valueType }, Assertions::<V> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReferenceArray}, assuming {@code Object} as element type.
*
* @see #atomicReferenceArray(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicReferenceArray, AtomicReferenceArrayAssert<Object>> ATOMIC_REFERENCE_ARRAY = atomicReferenceArray(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReferenceArray}.
*
* @param <E> the {@code AtomicReferenceArray} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #ATOMIC_REFERENCE_ARRAY
*/
@SuppressWarnings("rawtypes")
static <E> InstanceOfAssertFactory<AtomicReferenceArray, AtomicReferenceArrayAssert<E>> atomicReferenceArray(Class<E> elementType) {
return new InstanceOfAssertFactory<>(AtomicReferenceArray.class, new Class[] { elementType }, Assertions::<E> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReferenceFieldUpdater}, assuming {@code Object} as field and object types.
*
* @see #atomicReferenceFieldUpdater(Class, Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicReferenceFieldUpdater, AtomicReferenceFieldUpdaterAssert<Object, Object>> ATOMIC_REFERENCE_FIELD_UPDATER = atomicReferenceFieldUpdater(Object.class,
Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicReferenceFieldUpdater}.
*
* @param <T> the {@code AtomicReferenceFieldUpdater} field type.
* @param <V> the {@code AtomicReferenceFieldUpdater} object type.
* @param fieldType the field type instance.
* @param objectType the object type instance.
* @return the factory instance.
*
* @see #ATOMIC_REFERENCE_FIELD_UPDATER
*/
@SuppressWarnings("rawtypes")
static <T, V> InstanceOfAssertFactory<AtomicReferenceFieldUpdater, AtomicReferenceFieldUpdaterAssert<T, V>> atomicReferenceFieldUpdater(Class<T> fieldType,
Class<V> objectType) {
return new InstanceOfAssertFactory<>(AtomicReferenceFieldUpdater.class, new Class[] { fieldType, objectType },
Assertions::<T, V> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicMarkableReference}, assuming {@code Object} as value type.
*
* @see #atomicMarkableReference(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicMarkableReference, AtomicMarkableReferenceAssert<Object>> ATOMIC_MARKABLE_REFERENCE = atomicMarkableReference(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicMarkableReference}.
*
* @param <V> the {@code AtomicMarkableReference} value type.
* @param valueType the value type instance.
* @return the factory instance.
*
* @see #ATOMIC_MARKABLE_REFERENCE
*/
@SuppressWarnings("rawtypes")
static <V> InstanceOfAssertFactory<AtomicMarkableReference, AtomicMarkableReferenceAssert<V>> atomicMarkableReference(Class<V> valueType) {
return new InstanceOfAssertFactory<>(AtomicMarkableReference.class, new Class[] { valueType }, Assertions::<V> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicStampedReference}, assuming {@code Object} as value type.
*
* @see #atomicStampedReference(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<AtomicStampedReference, AtomicStampedReferenceAssert<Object>> ATOMIC_STAMPED_REFERENCE = atomicStampedReference(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link AtomicStampedReference}.
*
* @param <V> the {@code AtomicStampedReference} value type.
* @param valueType the value type instance.
* @return the factory instance.
*
* @see #ATOMIC_STAMPED_REFERENCE
*/
@SuppressWarnings("rawtypes")
static <V> InstanceOfAssertFactory<AtomicStampedReference, AtomicStampedReferenceAssert<V>> atomicStampedReference(Class<V> valueType) {
return new InstanceOfAssertFactory<>(AtomicStampedReference.class, new Class[] { valueType }, Assertions::<V> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Throwable}.
*/
InstanceOfAssertFactory<Throwable, AbstractThrowableAssert<?, Throwable>> THROWABLE = new InstanceOfAssertFactory<>(Throwable.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Throwable}.
*
* @param <T> the {@code Throwable} type.
* @param type the element type instance.
* @return the factory instance.
*
* @see #THROWABLE
* @since 3.21.0
*/
static <T extends Throwable> InstanceOfAssertFactory<T, AbstractThrowableAssert<?, T>> throwable(Class<T> type) {
return new InstanceOfAssertFactory<>(type, Assertions::assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link SQLException}.
*/
InstanceOfAssertFactory<SQLException, AbstractThrowableAssert<?, SQLException>> SQL_EXCEPTION = new InstanceOfAssertFactory<>(SQLException.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link SQLException}.
*
* @param <T> the {@code SQLException} type.
* @param type the element type instance.
* @return the factory instance.
*
* @see #SQL_EXCEPTION
* @since 4.0.0
*/
static <T extends SQLException> InstanceOfAssertFactory<T, AbstractThrowableAssert<?, T>> sqlException(Class<T> type) {
return new InstanceOfAssertFactory<>(type, Assertions::assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link CharSequence}.
*/
InstanceOfAssertFactory<CharSequence, AbstractCharSequenceAssert<?, ? extends CharSequence>> CHAR_SEQUENCE = new InstanceOfAssertFactory<>(CharSequence.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link StringBuilder}.
*/
InstanceOfAssertFactory<StringBuilder, AbstractCharSequenceAssert<?, ? extends CharSequence>> STRING_BUILDER = new InstanceOfAssertFactory<>(StringBuilder.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link StringBuffer}.
*/
InstanceOfAssertFactory<StringBuffer, AbstractCharSequenceAssert<?, ? extends CharSequence>> STRING_BUFFER = new InstanceOfAssertFactory<>(StringBuffer.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link String}.
*/
InstanceOfAssertFactory<String, AbstractStringAssert<?>> STRING = new InstanceOfAssertFactory<>(String.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link Iterable}, assuming {@code Object} as element type.
*
* @see #iterable(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Iterable, IterableAssert<Object>> ITERABLE = iterable(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link Iterable}.
*
* @param <ELEMENT> the {@code Iterable} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #ITERABLE
*/
@SuppressWarnings("rawtypes")
static <ELEMENT> InstanceOfAssertFactory<Iterable, IterableAssert<ELEMENT>> iterable(Class<ELEMENT> elementType) {
return new InstanceOfAssertFactory<>(Iterable.class, new Class[] { elementType }, Assertions::<ELEMENT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for an {@link Iterator}, assuming {@code Object} as element type.
*
* @see #iterator(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Iterator, IteratorAssert<Object>> ITERATOR = iterator(Object.class);
/**
* {@link InstanceOfAssertFactory} for an {@link Iterator}.
*
* @param <ELEMENT> the {@code Iterator} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #ITERATOR
*/
@SuppressWarnings("rawtypes")
static <ELEMENT> InstanceOfAssertFactory<Iterator, IteratorAssert<ELEMENT>> iterator(Class<ELEMENT> elementType) {
return new InstanceOfAssertFactory<>(Iterator.class, new Class[] { elementType }, Assertions::<ELEMENT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Collection}, assuming {@code Object} as element type.
*
* @see #collection(Class)
* @since 3.21.0
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Collection, AbstractCollectionAssert<?, Collection<?>, Object, ObjectAssert<Object>>> COLLECTION = collection(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Collection}.
*
* @param <E> the {@code Collection} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #COLLECTION
* @since 3.21.0
*/
@SuppressWarnings("rawtypes")
static <E> InstanceOfAssertFactory<Collection, AbstractCollectionAssert<?, Collection<? extends E>, E, ObjectAssert<E>>> collection(Class<E> elementType) {
return new InstanceOfAssertFactory<>(Collection.class, new Class[] { elementType }, Assertions::<E> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link List}, assuming {@code Object} as element type.
*
* @see #list(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<List, ListAssert<Object>> LIST = list(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link List}.
*
* @param <ELEMENT> the {@code List} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #LIST
*/
@SuppressWarnings("rawtypes")
static <ELEMENT> InstanceOfAssertFactory<List, ListAssert<ELEMENT>> list(Class<ELEMENT> elementType) {
return new InstanceOfAssertFactory<>(List.class, new Class[] { elementType }, Assertions::<ELEMENT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Set}, assuming {@code Object} as element type.
*
* @see #set(Class)
* @since 3.26.0
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Set, AbstractCollectionAssert<?, Collection<?>, Object, ObjectAssert<Object>>> SET = set(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Set}.
*
* @param <E> the {@code Set} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #SET
* @since 3.26.0
*/
@SuppressWarnings("rawtypes")
static <E> InstanceOfAssertFactory<Set, AbstractCollectionAssert<?, Collection<? extends E>, E, ObjectAssert<E>>> set(Class<E> elementType) {
return new InstanceOfAssertFactory<>(Set.class, new Class[] { elementType }, Assertions::<E> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link HashSet}, assuming {@code Object} as element type.
*
* @see #hashSet(Class)
* @since 4.0.0
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<HashSet, HashSetAssert<Object>> HASH_SET = hashSet(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link HashSet}.
*
* @param <E> the {@code HashSet} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #HASH_SET
* @since 3.26.0
*/
@SuppressWarnings("rawtypes")
static <E> InstanceOfAssertFactory<HashSet, HashSetAssert<E>> hashSet(Class<E> elementType) {
return new InstanceOfAssertFactory<>(HashSet.class, new Class[] { elementType }, Assertions::<E> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Stream}, assuming {@code Object} as element type.
*
* @see #stream(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Stream, ListAssert<Object>> STREAM = stream(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Stream}.
*
* @param <ELEMENT> the {@code Stream} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #STREAM
*/
@SuppressWarnings("rawtypes")
static <ELEMENT> InstanceOfAssertFactory<Stream, ListAssert<ELEMENT>> stream(Class<ELEMENT> elementType) {
return new InstanceOfAssertFactory<>(Stream.class, new Class[] { elementType }, Assertions::<ELEMENT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link DoubleStream}.
*/
InstanceOfAssertFactory<DoubleStream, ListAssert<Double>> DOUBLE_STREAM = new InstanceOfAssertFactory<>(DoubleStream.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link LongStream}.
*/
InstanceOfAssertFactory<LongStream, ListAssert<Long>> LONG_STREAM = new InstanceOfAssertFactory<>(LongStream.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for an {@link IntStream}.
*/
InstanceOfAssertFactory<IntStream, ListAssert<Integer>> INT_STREAM = new InstanceOfAssertFactory<>(IntStream.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Path}.
*/
InstanceOfAssertFactory<Path, AbstractPathAssert<?>> PATH = new InstanceOfAssertFactory<>(Path.class,
Assertions::assertThat);
/**
* {@link InstanceOfAssertFactory} for a {@link Spliterator}, assuming {@code Object} as element type.
*
* @see #spliterator(Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Spliterator, SpliteratorAssert<Object>> SPLITERATOR = spliterator(Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Spliterator}.
*
* @param <ELEMENT> the {@code Spliterator} element type.
* @param elementType the element type instance.
* @return the factory instance.
*
* @see #SPLITERATOR
*/
@SuppressWarnings("rawtypes")
static <ELEMENT> InstanceOfAssertFactory<Spliterator, SpliteratorAssert<ELEMENT>> spliterator(Class<ELEMENT> elementType) {
return new InstanceOfAssertFactory<>(Spliterator.class, new Class[] { elementType }, Assertions::<ELEMENT> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Map}, assuming {@code Object} as key and value types.
*
* @see #map(Class, Class)
*/
@SuppressWarnings("rawtypes")
InstanceOfAssertFactory<Map, MapAssert<Object, Object>> MAP = map(Object.class, Object.class);
/**
* {@link InstanceOfAssertFactory} for a {@link Map}.
*
* @param <K> the {@code Map} key type.
* @param <V> the {@code Map} value type.
* @param keyType the key type instance.
* @param valueType the value type instance.
* @return the factory instance.
*
* @see #MAP
*/
@SuppressWarnings("rawtypes")
static <K, V> InstanceOfAssertFactory<Map, MapAssert<K, V>> map(Class<K> keyType, Class<V> valueType) {
return new InstanceOfAssertFactory<>(Map.class, new Class[] { keyType, valueType }, Assertions::<K, V> assertThat);
}
/**
* {@link InstanceOfAssertFactory} for a {@link Comparable}.
*
* @param <T> the {@code Comparable} type.
* @param comparableType the comparable type instance.
* @return the factory instance.
*/
static <T extends Comparable<? super T>> InstanceOfAssertFactory<T, AbstractComparableAssert<?, T>> comparable(Class<T> comparableType) {
return new InstanceOfAssertFactory<>(comparableType, Assertions::assertThat);
}
}
|
InstanceOfAssertFactories
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/collection/wildcard/CunningPlan.java
|
{
"start": 309,
"end": 798
}
|
class ____ {
private BigDecimal content;
private JAXBElement<? super BigDecimal> description;
public BigDecimal getContent() {
return content;
}
public void setContent(BigDecimal content) {
this.content = content;
}
public JAXBElement<? super BigDecimal> getDescription() {
return description;
}
public void setDescription(JAXBElement<? super BigDecimal> description) {
this.description = description;
}
}
|
CunningPlan
|
java
|
google__dagger
|
dagger-spi/main/java/dagger/spi/model/BindingGraphPlugin.java
|
{
"start": 873,
"end": 2586
}
|
interface ____ {
/**
* Called once for each valid root binding graph encountered by the Dagger processor. May report
* diagnostics using {@code diagnosticReporter}.
*/
void visitGraph(BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter);
/**
* Initializes this plugin with a {@link DaggerProcessingEnv}.
*
* <p>This will be called once per instance of this plugin, before any graph is
* {@linkplain #visitGraph(BindingGraph, DiagnosticReporter) visited}.
*/
default void init(DaggerProcessingEnv processingEnv, Map<String, String> options) {}
/**
* Returns the annotation-processing options that this plugin uses to configure behavior.
*
* @see javax.annotation.processing.Processor#getSupportedOptions()
*/
default Set<String> supportedOptions() {
return Collections.emptySet();
}
/**
* A distinguishing name of the plugin that will be used in diagnostics printed to the messager.
* By default, the {@linkplain Class#getCanonicalName() fully qualified name} of the plugin is
* used.
*/
default String pluginName() {
return getClass().getCanonicalName();
}
/**
* Runs before each round of Dagger annotation processing.
*
* <p>If using the plugin to process elements that need resetting at the beginning of each
* processing round, use this function to perform the setup.
*/
default void onProcessingRoundBegin() {}
/**
* Perform any extra work after the plugin finished all its visiting. This will be called once per
* instance of this plugin, after all graphs were {@linkplain #visitGraph(BindingGraph,
* DiagnosticReporter) visited}
*/
default void onPluginEnd() {}
}
|
BindingGraphPlugin
|
java
|
spring-projects__spring-security
|
cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java
|
{
"start": 1061,
"end": 2340
}
|
class ____ implements StatelessTicketCache {
private static final Log logger = LogFactory.getLog(SpringCacheBasedTicketCache.class);
private final Cache cache;
public SpringCacheBasedTicketCache(Cache cache) {
Assert.notNull(cache, "cache mandatory");
this.cache = cache;
}
@Override
public @Nullable CasAuthenticationToken getByTicketId(final String serviceTicket) {
final Cache.ValueWrapper element = (serviceTicket != null) ? this.cache.get(serviceTicket) : null;
logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; service ticket: " + serviceTicket));
return (element != null) ? (CasAuthenticationToken) element.get() : null;
}
@Override
public void putTicketInCache(final CasAuthenticationToken token) {
String key = token.getCredentials().toString();
logger.debug(LogMessage.of(() -> "Cache put: " + key));
this.cache.put(key, token);
}
@Override
public void removeTicketFromCache(final CasAuthenticationToken token) {
logger.debug(LogMessage.of(() -> "Cache remove: " + token.getCredentials().toString()));
this.removeTicketFromCache(token.getCredentials().toString());
}
@Override
public void removeTicketFromCache(final String serviceTicket) {
this.cache.evict(serviceTicket);
}
}
|
SpringCacheBasedTicketCache
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.java
|
{
"start": 5101,
"end": 5680
}
|
class ____ {
void f() {
// BUG: Diagnostic contains: missing argument for format specifier '%s'
String.format("%s %s %s", 42);
// BUG: Diagnostic contains: missing argument for format specifier '%s'
String.format("%s %s %s", 42, 42);
String.format("%s %s %s", 42, 42, 42);
}
}
""")
.doTest();
}
@Test
public void extraArguments() {
compilationHelper
.addSourceLines(
"Test.java",
"""
|
Test
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AReadOpContext.java
|
{
"start": 1456,
"end": 7132
}
|
class ____ extends S3AOpContext {
/**
* Path of read.
*/
private final Path path;
/**
* Initial input policy of the stream.
*/
private S3AInputPolicy inputPolicy;
/**
* How to detect and deal with the object being updated during read.
*/
private ChangeDetectionPolicy changeDetectionPolicy;
/**
* Readahead for GET operations/skip, etc.
*/
private long readahead;
private AuditSpan auditSpan;
/**
* Threshold for stream reads to switch to
* asynchronous draining.
*/
private long asyncDrainThreshold;
/**
* Vectored IO context for vectored read api
* in {@code S3AInputStream#readVectored(List, IntFunction)}.
*/
private final VectoredIOContext vectoredIOContext;
/** Thread-level IOStatistics aggregator. **/
private final IOStatisticsAggregator ioStatisticsAggregator;
/**
* Pool for any future IO.
*/
private ExecutorServiceFuturePool futurePool;
/**
* Instantiate.
* @param path path of read
* @param invoker invoker for normal retries.
* @param stats Filesystem statistics (may be null)
* @param instrumentation statistics context
* @param dstFileStatus target file status
* @param vectoredIOContext context for vectored read operation.
* @param ioStatisticsAggregator IOStatistics aggregator for each thread.
* @param futurePool Pool for any future IO
*/
public S3AReadOpContext(
final Path path,
Invoker invoker,
@Nullable FileSystem.Statistics stats,
S3AStatisticsContext instrumentation,
FileStatus dstFileStatus,
VectoredIOContext vectoredIOContext,
IOStatisticsAggregator ioStatisticsAggregator,
ExecutorServiceFuturePool futurePool) {
super(invoker, stats, instrumentation,
dstFileStatus);
this.path = requireNonNull(path);
this.vectoredIOContext = requireNonNull(vectoredIOContext, "vectoredIOContext");
this.ioStatisticsAggregator = ioStatisticsAggregator;
this.futurePool = futurePool;
}
/**
* validate the context.
* @return a read operation context ready for use.
*/
public S3AReadOpContext build() {
requireNonNull(inputPolicy, "inputPolicy");
requireNonNull(changeDetectionPolicy, "changeDetectionPolicy");
requireNonNull(auditSpan, "auditSpan");
requireNonNull(inputPolicy, "inputPolicy");
Preconditions.checkArgument(readahead >= 0,
"invalid readahead %d", readahead);
Preconditions.checkArgument(asyncDrainThreshold >= 0,
"invalid drainThreshold %d", asyncDrainThreshold);
requireNonNull(ioStatisticsAggregator, "ioStatisticsAggregator");
return this;
}
/**
* Get invoker to use for read operations.
* @return invoker to use for read codepaths
*/
public Invoker getReadInvoker() {
return invoker;
}
/**
* Get the path of this read.
* @return path.
*/
public Path getPath() {
return path;
}
/**
* Get the IO policy.
* @return the initial input policy.
*/
public S3AInputPolicy getInputPolicy() {
return inputPolicy;
}
public ChangeDetectionPolicy getChangeDetectionPolicy() {
return changeDetectionPolicy;
}
/**
* Get the readahead for this operation.
* @return a value {@literal >=} 0
*/
public long getReadahead() {
return readahead;
}
/**
* Get the audit which was active when the file was opened.
* @return active span
*/
public AuditSpan getAuditSpan() {
return auditSpan;
}
/**
* Set builder value.
* @param value new value
* @return the builder
*/
public S3AReadOpContext withInputPolicy(final S3AInputPolicy value) {
inputPolicy = value;
return this;
}
/**
* Set builder value.
* @param value new value
* @return the builder
*/
public S3AReadOpContext withChangeDetectionPolicy(
final ChangeDetectionPolicy value) {
changeDetectionPolicy = value;
return this;
}
/**
* Set builder value.
* @param value new value
* @return the builder
*/
public S3AReadOpContext withReadahead(final long value) {
readahead = value;
return this;
}
/**
* Set builder value.
* @param value new value
* @return the builder
*/
public S3AReadOpContext withAuditSpan(final AuditSpan value) {
auditSpan = value;
return this;
}
/**
* Set builder value.
* @param value new value
* @return the builder
*/
public S3AReadOpContext withAsyncDrainThreshold(final long value) {
asyncDrainThreshold = value;
return this;
}
public long getAsyncDrainThreshold() {
return asyncDrainThreshold;
}
/**
* Get Vectored IO context for this this read op.
* @return vectored IO context.
*/
public VectoredIOContext getVectoredIOContext() {
return vectoredIOContext;
}
/**
* Return the IOStatistics aggregator.
*
* @return instance of IOStatisticsAggregator.
*/
public IOStatisticsAggregator getIOStatisticsAggregator() {
return ioStatisticsAggregator;
}
/**
* Gets the {@code ExecutorServiceFuturePool} used for asynchronous prefetches.
*
* @return the {@code ExecutorServiceFuturePool} used for asynchronous prefetches.
*/
public ExecutorServiceFuturePool getFuturePool() {
return this.futurePool;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(
"S3AReadOpContext{");
sb.append("path=").append(path);
sb.append(", inputPolicy=").append(inputPolicy);
sb.append(", readahead=").append(readahead);
sb.append(", changeDetectionPolicy=").append(changeDetectionPolicy);
sb.append('}');
return sb.toString();
}
}
|
S3AReadOpContext
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/aot/JpaRepositoryMetadataIntegrationTests.java
|
{
"start": 1704,
"end": 6204
}
|
class ____ extends AotFragmentTestConfigurationSupport {
public JpaRepositoryContributorConfiguration() {
super(UserRepository.class);
}
}
@Test // GH-3830
void shouldDocumentBase() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).isObject() //
.containsEntry("name", UserRepository.class.getName()) //
.containsEntry("module", "JPA") //
.containsEntry("type", "IMPERATIVE");
}
@Test // GH-3830
void shouldDocumentDerivedQuery() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[0]").isObject().containsEntry("name", "countUsersByLastname");
assertThatJson(json).inPath("$.methods[0].query").isObject().containsEntry("query",
"SELECT COUNT(u) FROM User u WHERE u.lastname = :lastname");
}
@Test // GH-3830
void shouldDocumentPagedQuery() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'findAndApplyQueryRewriter')].query").isArray().element(1)
.isObject().containsEntry("query", "select u from OTHER u where u.emailAddress = ?1")
.containsEntry("count-query", "select count(u) from OTHER u where u.emailAddress = ?1");
}
@Test // GH-3830
void shouldDocumentQueryWithExpression() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'findValueExpressionNamedByEmailAddress')].query").isArray()
.first().isObject().containsEntry("query", "select u from User u where u.emailAddress = :__$synthetic$__1");
}
@Test // GH-3830
void shouldDocumentNamedQuery() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'findPagedWithNamedCountByEmailAddress')].query").isArray()
.first().isObject().containsEntry("name", "User.findByEmailAddress")
.containsEntry("query", "SELECT u FROM User u WHERE u.emailAddress = ?1")
.containsEntry("count-name", "User.findByEmailAddress.count-provided")
.containsEntry("count-query", "SELECT count(u) FROM User u WHERE u.emailAddress = ?1");
}
@Test // GH-3830
void shouldDocumentNamedProcedure() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'namedProcedure')].query").isArray().first().isObject()
.containsEntry("procedure-name", "User.plus1IO");
}
@Test // GH-3830
void shouldDocumentProvidedProcedure() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'providedProcedure')].query").isArray().first().isObject()
.containsEntry("procedure", "sp_add");
}
@Test // GH-3830
void shouldDocumentBaseFragment() throws IOException {
Resource resource = getResource();
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
String json = resource.getContentAsString(StandardCharsets.UTF_8);
assertThatJson(json).inPath("$.methods[?(@.name == 'existsById')].fragment").isArray().first().isObject()
.containsEntry("fragment", "org.springframework.data.jpa.repository.support.SimpleJpaRepository");
}
private Resource getResource() {
String location = UserRepository.class.getPackageName().replace('.', '/') + "/"
+ UserRepository.class.getSimpleName() + ".json";
return new UrlResource(context.getBeanFactory().getBeanClassLoader().getResource(location));
}
}
|
JpaRepositoryContributorConfiguration
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptor.java
|
{
"start": 12555,
"end": 18518
}
|
class ____<T extends TransportRequest> implements TransportRequestHandler<T> {
private final String action;
private final TransportRequestHandler<T> handler;
private final Map<String, ServerTransportFilter> profileFilters;
private final ThreadContext threadContext;
private final Executor executor;
private final ThreadPool threadPool;
private final boolean forceExecution;
private final Logger logger;
ProfileSecuredRequestHandler(
Logger logger,
String action,
boolean forceExecution,
Executor executor,
TransportRequestHandler<T> handler,
Map<String, ServerTransportFilter> profileFilters,
ThreadPool threadPool
) {
this.logger = logger;
this.action = action;
this.executor = executor;
this.handler = handler;
this.profileFilters = profileFilters;
this.threadContext = threadPool.getThreadContext();
this.threadPool = threadPool;
this.forceExecution = forceExecution;
}
AbstractRunnable getReceiveRunnable(T request, TransportChannel channel, Task task) {
final Runnable releaseRequest = new RunOnce(request::decRef);
request.mustIncRef();
return new AbstractRunnable() {
@Override
public boolean isForceExecution() {
return forceExecution;
}
@Override
public void onFailure(Exception e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
e1.addSuppressed(e);
logger.warn("failed to send exception response for action [" + action + "]", e1);
}
}
@Override
protected void doRun() throws Exception {
handler.messageReceived(request, channel, task);
}
@Override
public void onAfter() {
releaseRequest.run();
}
};
}
@Override
public String toString() {
return "ProfileSecuredRequestHandler{" + "action='" + action + '\'' + ", forceExecution=" + forceExecution + '}';
}
@Override
public void messageReceived(T request, TransportChannel channel, Task task) {
try (ThreadContext.StoredContext ctx = threadContext.newStoredContextPreservingResponseHeaders()) {
String profile = channel.getProfileName();
ServerTransportFilter filter = getServerTransportFilter(profile);
assert filter != null;
assert request != null;
logger.trace(
() -> format(
"Applying transport filter [%s] for transport profile [%s] on request [%s]",
filter.getClass(),
profile,
request.getClass()
)
);
final AbstractRunnable receiveMessage = getReceiveRunnable(request, channel, task);
final ActionListener<Void> filterListener;
if (executor == EsExecutors.DIRECT_EXECUTOR_SERVICE) {
filterListener = new AbstractFilterListener(receiveMessage) {
@Override
public void onResponse(Void unused) {
receiveMessage.run();
}
};
} else {
final Thread executingThread = Thread.currentThread();
filterListener = new AbstractFilterListener(receiveMessage) {
@Override
public void onResponse(Void unused) {
if (executingThread == Thread.currentThread()) {
// only fork off if we get called on another thread this means we moved to
// an async execution and in this case we need to go back to the thread pool
// that was actually executing it. it's also possible that the
// thread-pool we are supposed to execute on is `SAME` in that case
// the handler is OK with executing on a network thread and we can just continue even if
// we are on another thread due to async operations
receiveMessage.run();
} else {
try {
executor.execute(receiveMessage);
} catch (Exception e) {
onFailure(e);
}
}
}
};
}
filter.inbound(action, request, channel, filterListener);
}
}
private ServerTransportFilter getServerTransportFilter(String profile) {
final ServerTransportFilter filter = profileFilters.get(profile);
if (filter != null) {
return filter;
}
if (TransportService.DIRECT_RESPONSE_PROFILE.equals(profile)) {
// apply the default filter to local requests. We never know what the request is or who sent it...
return profileFilters.get("default");
} else {
String msg = "transport profile [" + profile + "] is not associated with a transport filter";
throw new IllegalStateException(msg);
}
}
}
private abstract static
|
ProfileSecuredRequestHandler
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/factories/a/BarFactory.java
|
{
"start": 278,
"end": 373
}
|
class ____ {
public Bar1 createBar1() {
return new Bar1( "BAR1" );
}
}
|
BarFactory
|
java
|
netty__netty
|
transport-native-io_uring/src/test/java/io/netty/channel/uring/IoUringDomainSocketAbstractFdTest.java
|
{
"start": 708,
"end": 927
}
|
class ____ extends IoUringDomainSocketFdTest {
@Override
protected SocketAddress newSocketAddress() {
return IoUringSocketTestPermutation.newAbstractSocketAddress();
}
}
|
IoUringDomainSocketAbstractFdTest
|
java
|
quarkusio__quarkus
|
integration-tests/logging-min-level-unset/src/test/java/io/quarkus/it/logging/minlevel/unset/LoggingMinLevelPromoteTest.java
|
{
"start": 586,
"end": 1242
}
|
class ____ {
@Test
public void testInfo() {
given()
.when().get("/log/promote/info")
.then()
.statusCode(200)
.body(is("true"));
}
@Test
public void testWarn() {
given()
.when().get("/log/promote/warn")
.then()
.statusCode(200)
.body(is("true"));
}
@Test
public void testNotTrace() {
given()
.when().get("/log/promote/not-trace")
.then()
.statusCode(200)
.body(is("true"));
}
}
|
LoggingMinLevelPromoteTest
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/InflightRepository.java
|
{
"start": 1011,
"end": 1133
}
|
interface ____ extends StaticService {
/**
* Information about the inflight exchange.
*/
|
InflightRepository
|
java
|
lettuce-io__lettuce-core
|
src/test/java/io/lettuce/core/search/RedisJsonIndexingResp2IntegrationTests.java
|
{
"start": 981,
"end": 1224
}
|
class ____ extends RedisJsonIndexingIntegrationTests {
@Override
protected ClientOptions getOptions() {
return ClientOptions.builder().protocolVersion(ProtocolVersion.RESP2).build();
}
}
|
RedisJsonIndexingResp2IntegrationTests
|
java
|
apache__camel
|
components/camel-ibm/camel-ibm-cos/src/main/java/org/apache/camel/component/ibm/cos/IBMCOSEndpoint.java
|
{
"start": 2347,
"end": 8252
}
|
class ____ extends ScheduledPollEndpoint implements EndpointServiceLocation {
private static final Logger LOG = LoggerFactory.getLogger(IBMCOSEndpoint.class);
private static final int DEFAULT_IN_PROGRESS_CACHE_SIZE = 10000;
private AmazonS3 cosClient;
@UriPath(description = "Bucket name")
@Metadata(required = true)
private String bucketName;
@UriParam
private IBMCOSConfiguration configuration;
@UriParam(label = "consumer", defaultValue = "10")
private int maxMessagesPerPoll = 10;
@UriParam(label = "consumer,advanced")
private IdempotentRepository inProgressRepository
= MemoryIdempotentRepository.memoryIdempotentRepository(DEFAULT_IN_PROGRESS_CACHE_SIZE);
public IBMCOSEndpoint(String uri, Component comp, IBMCOSConfiguration configuration) {
super(uri, comp);
this.configuration = configuration;
}
@Override
public String getServiceUrl() {
if (ObjectHelper.isNotEmpty(configuration.getEndpointUrl())) {
return configuration.getEndpointUrl() + "/" + configuration.getBucketName();
}
return null;
}
@Override
public String getServiceProtocol() {
return "cos";
}
@Override
public Map<String, String> getServiceMetadata() {
if (configuration.getLocation() != null) {
return Map.of("location", configuration.getLocation());
}
return null;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
IBMCOSConsumer cosConsumer = new IBMCOSConsumer(this, processor);
configureConsumer(cosConsumer);
cosConsumer.setMaxMessagesPerPoll(maxMessagesPerPoll);
return cosConsumer;
}
@Override
public Producer createProducer() throws Exception {
return new IBMCOSProducer(this);
}
@Override
public IBMCOSComponent getComponent() {
return (IBMCOSComponent) super.getComponent();
}
@Override
protected void doStart() throws Exception {
super.doStart();
cosClient = configuration.getCosClient() != null
? configuration.getCosClient() : createCosClient();
String fileName = getConfiguration().getFileName();
if (fileName != null) {
LOG.trace("File name [{}] requested, so skipping bucket check...", fileName);
return;
}
String bucketName = getConfiguration().getBucketName();
LOG.trace("Querying whether bucket [{}] already exists...", bucketName);
try {
boolean bucketExists = cosClient.doesBucketExistV2(bucketName);
if (bucketExists) {
LOG.trace("Bucket [{}] already exists", bucketName);
return;
}
} catch (Exception e) {
LOG.warn("Error checking if bucket exists: {}", e.getMessage());
}
LOG.trace("Bucket [{}] doesn't exist yet", bucketName);
if (getConfiguration().isAutoCreateBucket()) {
LOG.trace("Creating bucket [{}]...", bucketName);
// The location is specified via the client's endpoint configuration
cosClient.createBucket(bucketName);
LOG.trace("Bucket created");
}
ServiceHelper.startService(inProgressRepository);
}
@Override
protected void doStop() throws Exception {
if (ObjectHelper.isEmpty(configuration.getCosClient())) {
if (cosClient != null) {
cosClient.shutdown();
}
}
ServiceHelper.stopService(inProgressRepository);
super.doStop();
}
private AmazonS3 createCosClient() {
AWSCredentials credentials;
if (configuration.getApiKey() != null) {
credentials = new BasicIBMOAuthCredentials(
configuration.getApiKey(),
configuration.getServiceInstanceId());
} else {
throw new IllegalArgumentException("API Key must be provided");
}
ClientConfiguration clientConfig = new ClientConfiguration()
.withRequestTimeout(5000)
.withTcpKeepAlive(true);
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withPathStyleAccessEnabled(true)
.withClientConfiguration(clientConfig);
if (configuration.getEndpointUrl() != null) {
// For IBM COS, use null as the signing region - it will be determined from the endpoint
builder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
configuration.getEndpointUrl(),
null));
}
return builder.build();
}
public IBMCOSConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(IBMCOSConfiguration configuration) {
this.configuration = configuration;
}
public AmazonS3 getCosClient() {
return cosClient;
}
public void setCosClient(AmazonS3 cosClient) {
this.cosClient = cosClient;
}
public int getMaxMessagesPerPoll() {
return maxMessagesPerPoll;
}
/**
* Gets the maximum number of messages as a limit to poll at each polling.
*/
public void setMaxMessagesPerPoll(int maxMessagesPerPoll) {
this.maxMessagesPerPoll = maxMessagesPerPoll;
}
public IdempotentRepository getInProgressRepository() {
return inProgressRepository;
}
/**
* A pluggable in-progress repository to track objects being consumed
*/
public void setInProgressRepository(IdempotentRepository inProgressRepository) {
this.inProgressRepository = inProgressRepository;
}
}
|
IBMCOSEndpoint
|
java
|
spring-projects__spring-framework
|
spring-aop/src/main/java/org/springframework/aop/aspectj/RuntimeTestWalker.java
|
{
"start": 7567,
"end": 8664
}
|
class ____ extends TestVisitorAdapter {
private final Object thisObj = new Object();
private final Object targetObj = new Object();
private final Object[] argsObjs = new Object[0];
private boolean testsSubtypeSensitiveVars = false;
public boolean testsSubtypeSensitiveVars(Test aTest) {
aTest.accept(this);
return this.testsSubtypeSensitiveVars;
}
@Override
public void visit(Instanceof i) {
ReflectionVar v = (ReflectionVar) i.getVar();
Object varUnderTest = v.getBindingAtJoinPoint(this.thisObj, this.targetObj, this.argsObjs);
if (varUnderTest == this.thisObj || varUnderTest == this.targetObj) {
this.testsSubtypeSensitiveVars = true;
}
}
@Override
public void visit(HasAnnotation hasAnn) {
// If you thought things were bad before, now we sink to new levels of horror...
ReflectionVar v = (ReflectionVar) hasAnn.getVar();
int varType = getVarType(v);
if (varType == AT_THIS_VAR || varType == AT_TARGET_VAR || varType == AT_ANNOTATION_VAR) {
this.testsSubtypeSensitiveVars = true;
}
}
}
}
|
SubtypeSensitiveVarTypeTestVisitor
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java
|
{
"start": 2814,
"end": 19794
}
|
class ____ {
private ClientRegistration registration1;
private ClientRegistration registration2;
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizationRequestRedirectFilter filter;
private RequestCache requestCache;
@BeforeEach
public void setUp() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.registration2 = TestClientRegistrations.clientRegistration2().build();
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2);
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository);
this.requestCache = mock(RequestCache.class);
this.filter.setRequestCache(this.requestCache);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
Constructor<OAuth2AuthorizationRequestRedirectFilter> constructor = ClassUtils.getConstructorIfAvailable(
OAuth2AuthorizationRequestRedirectFilter.class, ClientRegistrationRepository.class);
assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null));
}
@Test
public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, null));
}
@Test
public void constructorWhenAuthorizationRequestResolverIsNullThenThrowIllegalArgumentException() {
Constructor<OAuth2AuthorizationRequestRedirectFilter> constructor = ClassUtils.getConstructorIfAvailable(
OAuth2AuthorizationRequestRedirectFilter.class, OAuth2AuthorizationRequestResolver.class);
assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null));
}
@Test
public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null));
}
@Test
public void setAuthorizationRedirectStrategyWhenAuthorizationRedirectStrategyIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRedirectStrategy(null));
}
@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null));
}
@Test
public void setAuthenticationFailureHandlerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationFailureHandler(null));
}
@Test
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientAndCustomFailureHandlerThenCustomError()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.setAuthenticationFailureHandler((request1, response1, ex) -> {
Throwable cause = ex.getCause();
if (InvalidClientRegistrationIdException.class.isAssignableFrom(cause.getClass())) {
response1.sendError(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase());
}
else {
response1.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
});
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase());
}
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenRedirectForAuthorization() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration2.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(
AuthorizationRequestRepository.class);
this.filter.setAuthorizationRequestRepository(authorizationRequestRepository);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(authorizationRequestRepository).saveAuthorizationRequest(any(OAuth2AuthorizationRequest.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenCustomAuthorizationRequestBaseUriThenRedirectForAuthorization() throws Exception {
String authorizationRequestBaseUri = "/custom/authorization";
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository,
authorizationRequestBaseUri);
String requestUri = authorizationRequestBaseUri + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenRedirectForAuthorization()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
verify(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownButAuthorizationRequestNotResolvedThenStatusInternalServerError()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
// gh-4911
@Test
public void doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
request.addParameter("idp", "https://other.provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(
this.clientRegistrationRepository,
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest
.from(defaultAuthorizationRequestResolver.resolve(request))
.additionalParameters(Collections.singletonMap("idp", request.getParameter("idp")))
.build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256&idp=https://other.provider.com");
}
// gh-4911, gh-5244
@Test
public void doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
String loginHintParamName = "login_hint";
request.addParameter(loginHintParamName, "user@provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(
this.clientRegistrationRepository,
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest defaultAuthorizationRequest = defaultAuthorizationRequestResolver.resolve(request);
Map<String, Object> additionalParameters = new HashMap<>(defaultAuthorizationRequest.getAdditionalParameters());
additionalParameters.put(loginHintParamName, request.getParameter(loginHintParamName));
// @formatter:off
String customAuthorizationRequestUri = UriComponentsBuilder
.fromUriString(defaultAuthorizationRequest.getAuthorizationRequestUri())
.queryParam(loginHintParamName, additionalParameters.get(loginHintParamName))
.build(true)
.toUriString();
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest
.from(defaultAuthorizationRequestResolver.resolve(request))
.additionalParameters(Collections.singletonMap("idp", request.getParameter("idp")))
.authorizationRequestUri(customAuthorizationRequestUri)
.build();
// @formatter:on
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256&login_hint=user@provider\\.com");
}
@Test
public void doFilterWhenCustomAuthorizationRedirectStrategySetThenCustomAuthorizationRedirectStrategyUsed()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
RedirectStrategy customRedirectStrategy = (httpRequest, httpResponse, url) -> {
String redirectUrl = httpResponse.encodeRedirectURL(url);
httpResponse.setStatus(HttpStatus.OK.value());
httpResponse.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
httpResponse.getWriter().write(redirectUrl);
httpResponse.getWriter().flush();
};
this.filter.setAuthorizationRedirectStrategy(customRedirectStrategy);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(response.getContentAsString(StandardCharsets.UTF_8))
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
// gh-11602
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenSaveRequestBeforeCommitted()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willAnswer((invocation) -> assertThat((invocation.<HttpServletResponse>getArgument(1)).isCommitted()).isFalse())
.given(this.requestCache)
.saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
assertThat(response.isCommitted()).isTrue();
}
}
|
OAuth2AuthorizationRequestRedirectFilterTests
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/ExtendsAutoValue.java
|
{
"start": 3757,
"end": 4160
}
|
class ____ non-generated code.", name))
.build();
})
.orElse(Description.NO_MATCH);
}
private static boolean isInGeneratedCode(VisitorState state) {
// Skip generated code. Yes, I know we can do this via a flag but we should always ignore
// generated code, so to be sure, manually check it.
return !ASTHelpers.getGeneratedBy(state).isEmpty();
}
}
|
in
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapTask.java
|
{
"start": 17283,
"end": 20958
}
|
class ____<K,V>
extends org.apache.hadoop.mapreduce.RecordReader<K,V> {
private final org.apache.hadoop.mapreduce.RecordReader<K,V> real;
private final org.apache.hadoop.mapreduce.Counter inputRecordCounter;
private final org.apache.hadoop.mapreduce.Counter fileInputByteCounter;
private final TaskReporter reporter;
private final List<Statistics> fsStats;
NewTrackingRecordReader(org.apache.hadoop.mapreduce.InputSplit split,
org.apache.hadoop.mapreduce.InputFormat<K, V> inputFormat,
TaskReporter reporter,
org.apache.hadoop.mapreduce.TaskAttemptContext taskContext)
throws InterruptedException, IOException {
this.reporter = reporter;
this.inputRecordCounter = reporter
.getCounter(TaskCounter.MAP_INPUT_RECORDS);
this.fileInputByteCounter = reporter
.getCounter(FileInputFormatCounter.BYTES_READ);
List <Statistics> matchedStats = null;
if (split instanceof org.apache.hadoop.mapreduce.lib.input.FileSplit) {
matchedStats = getFsStatistics(((org.apache.hadoop.mapreduce.lib.input.FileSplit) split)
.getPath(), taskContext.getConfiguration());
}
fsStats = matchedStats;
long bytesInPrev = getInputBytes(fsStats);
this.real = inputFormat.createRecordReader(split, taskContext);
long bytesInCurr = getInputBytes(fsStats);
fileInputByteCounter.increment(bytesInCurr - bytesInPrev);
}
@Override
public void close() throws IOException {
long bytesInPrev = getInputBytes(fsStats);
real.close();
long bytesInCurr = getInputBytes(fsStats);
fileInputByteCounter.increment(bytesInCurr - bytesInPrev);
}
@Override
public K getCurrentKey() throws IOException, InterruptedException {
return real.getCurrentKey();
}
@Override
public V getCurrentValue() throws IOException, InterruptedException {
return real.getCurrentValue();
}
@Override
public float getProgress() throws IOException, InterruptedException {
return real.getProgress();
}
@Override
public void initialize(org.apache.hadoop.mapreduce.InputSplit split,
org.apache.hadoop.mapreduce.TaskAttemptContext context
) throws IOException, InterruptedException {
long bytesInPrev = getInputBytes(fsStats);
real.initialize(split, context);
long bytesInCurr = getInputBytes(fsStats);
fileInputByteCounter.increment(bytesInCurr - bytesInPrev);
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
long bytesInPrev = getInputBytes(fsStats);
boolean result = real.nextKeyValue();
long bytesInCurr = getInputBytes(fsStats);
if (result) {
inputRecordCounter.increment(1);
}
fileInputByteCounter.increment(bytesInCurr - bytesInPrev);
reporter.setProgress(getProgress());
return result;
}
private long getInputBytes(List<Statistics> stats) {
if (stats == null) return 0;
long bytesRead = 0;
for (Statistics stat: stats) {
bytesRead = bytesRead + stat.getBytesRead();
}
return bytesRead;
}
}
/**
* Since the mapred and mapreduce Partitioners don't share a common interface
* (JobConfigurable is deprecated and a subtype of mapred.Partitioner), the
* partitioner lives in Old/NewOutputCollector. Note that, for map-only jobs,
* the configured partitioner should not be called. It's common for
* partitioners to compute a result mod numReduces, which causes a div0 error
*/
private static
|
NewTrackingRecordReader
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java
|
{
"start": 17621,
"end": 17837
}
|
class ____ encapsulates a specific set of target listeners,
* allowing for efficient retrieval of pre-filtered listeners.
* <p>An instance of this helper gets cached per event type and source type.
*/
private
|
that
|
java
|
spring-projects__spring-boot
|
module/spring-boot-thymeleaf/src/test/java/org/springframework/boot/thymeleaf/autoconfigure/ThymeleafServletAutoConfigurationTests.java
|
{
"start": 3657,
"end": 15783
}
|
class ____ {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class));
@Test
void autoConfigurationBackOffWithoutThymeleafSpring() {
this.contextRunner.withClassLoader(new FilteredClassLoader("org.thymeleaf.spring6"))
.run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class));
}
@Test
@WithResource(name = "templates/template.html", content = "<html th:text=\"${foo}\">foo</html>")
void createFromConfigClass() {
this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:")
.run((context) -> {
assertThat(context).hasSingleBean(TemplateEngine.class);
TemplateEngine engine = context.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar"));
String result = engine.process("template.html", attrs).trim();
assertThat(result).isEqualTo("<html>bar</html>");
});
}
@Test
void overrideCharacterEncoding() {
this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16").run((context) -> {
ITemplateResolver resolver = context.getBean(ITemplateResolver.class);
assertThat(resolver).isInstanceOf(SpringResourceTemplateResolver.class);
assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16");
ThymeleafViewResolver views = context.getBean(ThymeleafViewResolver.class);
assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16");
assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16");
});
}
@Test
void overrideDisableProducePartialOutputWhileProcessing() {
this.contextRunner.withPropertyValues("spring.thymeleaf.servlet.produce-partial-output-while-processing:false")
.run((context) -> assertThat(
context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing())
.isFalse());
}
@Test
void disableProducePartialOutputWhileProcessingIsEnabledByDefault() {
this.contextRunner.run((context) -> assertThat(
context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing())
.isTrue());
}
@Test
void overrideTemplateResolverOrder() {
this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25")
.run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder())
.isEqualTo(Integer.valueOf(25)));
}
@Test
void overrideViewNames() {
this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar")
.run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames())
.isEqualTo(new String[] { "foo", "bar" }));
}
@Test
void overrideEnableSpringElCompiler() {
this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true")
.run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler())
.isTrue());
}
@Test
void enableSpringElCompilerIsDisabledByDefault() {
this.contextRunner
.run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler())
.isFalse());
}
@Test
void overrideRenderHiddenMarkersBeforeCheckboxes() {
this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true")
.run((context) -> assertThat(
context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes())
.isTrue());
}
@Test
void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() {
this.contextRunner.run((context) -> assertThat(
context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes())
.isFalse());
}
@Test
void templateLocationDoesNotExist(CapturedOutput output) {
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/")
.run((context) -> assertThat(output).contains("Cannot find template location"));
}
@Test
void templateLocationEmpty(CapturedOutput output, @TempDir Path tempDir) throws IOException {
Path directory = tempDir.resolve("empty-templates/empty-directory").toAbsolutePath();
Files.createDirectories(directory);
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:file:" + directory)
.run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
}
@Test
@WithResource(name = "templates/view.html",
content = """
<html xmlns:th="https://www.thymeleaf.org" xmlns:layout="https://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorator="layout">
<head>
<title layout:fragment="title">Content</title>
</head>
<body>
<div layout:fragment="content">
<span th:text="${foo}">foo</span>
</div>
</body>
</html>
""")
void createLayoutFromConfigClass() {
this.contextRunner.run((context) -> {
ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class)
.resolveViewName("view", Locale.UK);
assertThat(view).isNotNull();
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest(context.getBean(ServletContext.class));
request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
view.render(Collections.singletonMap("foo", "bar"), request, response);
String result = response.getContentAsString();
assertThat(result).contains("<title>Content</title>");
assertThat(result).contains("<span>bar</span>");
context.close();
});
}
@Test
@WithResource(name = "templates/data-dialect.html", content = "<html><body data:foo=\"${foo}\"></body></html>")
void useDataDialect() {
this.contextRunner.run((context) -> {
TemplateEngine engine = context.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar"));
String result = engine.process("data-dialect", attrs).trim();
assertThat(result).isEqualTo("<html><body data-foo=\"bar\"></body></html>");
});
}
@Test
@WithResource(name = "templates/java8time-dialect.html",
content = "<html><body th:text=\"${#temporals.create('2015','11','24')}\"></body></html>")
void useJava8TimeDialect() {
this.contextRunner.run((context) -> {
TemplateEngine engine = context.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK);
String result = engine.process("java8time-dialect", attrs).trim();
assertThat(result).isEqualTo("<html><body>2015-11-24</body></html>");
});
}
@Test
@WithResource(name = "templates/security-dialect.html",
content = "<html><body><div sec:authentication=\"name\"></div></body></html>")
void useSecurityDialect() {
this.contextRunner.run((context) -> {
TemplateEngine engine = context.getBean(TemplateEngine.class);
MockServletContext servletContext = new MockServletContext();
JakartaServletWebApplication webApplication = JakartaServletWebApplication.buildApplication(servletContext);
WebContext attrs = new WebContext(webApplication.buildExchange(new MockHttpServletRequest(servletContext),
new MockHttpServletResponse()));
try {
SecurityContextHolder
.setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin")));
String result = engine.process("security-dialect", attrs);
assertThat(result).isEqualTo("<html><body><div>alice</div></body></html>");
}
finally {
SecurityContextHolder.clearContext();
}
});
}
@Test
void securityDialectAutoConfigurationBacksOffWithoutSpringSecurity() {
this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security"))
.run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class));
}
@Test
@WithResource(name = "templates/home.html", content = "<html><body th:text=\"${foo}\">Home</body></html>")
void renderTemplate() {
this.contextRunner.run((context) -> {
TemplateEngine engine = context.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar"));
String result = engine.process("home", attrs).trim();
assertThat(result).isEqualTo("<html><body>bar</body></html>");
});
}
@Test
@WithResource(name = "templates/message.html",
content = "<html><body>Message: <span th:text=\"${greeting}\">Hello</span></body></html>")
void renderNonWebAppTemplate() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class))
.run((context) -> {
assertThat(context).doesNotHaveBean(ViewResolver.class);
TemplateEngine engine = context.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World"));
String result = engine.process("message", attrs);
assertThat(result).contains("Hello World");
});
}
@Test
void registerResourceHandlingFilterDisabledByDefault() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class));
}
@Test
void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() {
this.contextRunner.withPropertyValues("spring.web.resources.chain.enabled:true").run((context) -> {
FilterRegistrationBean<?> registration = context.getBean(FilterRegistrationBean.class);
assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class);
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
});
}
@Test
@SuppressWarnings("rawtypes")
void registerResourceHandlingFilterWithOtherRegistrationBean() {
// gh-14897
this.contextRunner.withUserConfiguration(FilterRegistrationOtherConfiguration.class)
.withPropertyValues("spring.web.resources.chain.enabled:true")
.run((context) -> {
Map<String, FilterRegistrationBean> beans = context.getBeansOfType(FilterRegistrationBean.class);
assertThat(beans).hasSize(2);
FilterRegistrationBean registration = beans.values()
.stream()
.filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter)
.findFirst()
.get();
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
});
}
@Test
@SuppressWarnings("rawtypes")
void registerResourceHandlingFilterWithResourceRegistrationBean() {
// gh-14926
this.contextRunner.withUserConfiguration(FilterRegistrationResourceConfiguration.class)
.withPropertyValues("spring.web.resources.chain.enabled:true")
.run((context) -> {
Map<String, FilterRegistrationBean> beans = context.getBeansOfType(FilterRegistrationBean.class);
assertThat(beans).hasSize(1);
FilterRegistrationBean registration = beans.values()
.stream()
.filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter)
.findFirst()
.get();
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
EnumSet.of(DispatcherType.INCLUDE));
});
}
@Test
void layoutDialectCanBeCustomized() {
this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class)
.run((context) -> assertThat(
ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy"))
.isInstanceOf(GroupingStrategy.class));
}
@Test
void cachingCanBeDisabled() {
this.contextRunner.withPropertyValues("spring.thymeleaf.cache:false").run((context) -> {
Assertions.assertThat(context.getBean(ThymeleafViewResolver.class).isCache()).isFalse();
SpringResourceTemplateResolver templateResolver = context.getBean(SpringResourceTemplateResolver.class);
assertThat(templateResolver.isCacheable()).isFalse();
});
}
@Test
void missingAbstractCachingViewResolver() {
this.contextRunner.withClassLoader(new FilteredClassLoader(AbstractCachingViewResolver.class))
.run((context) -> assertThat(context).hasNotFailed().doesNotHaveBean("thymeleafViewResolver"));
}
@Configuration(proxyBeanMethods = false)
static
|
ThymeleafServletAutoConfigurationTests
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/conf/TestGetInstances.java
|
{
"start": 1290,
"end": 2719
}
|
class ____ implements ChildInterface {
AnotherClass() {}
}
/**
* Makes sure <code>Configuration.getInstances()</code> returns
* instances of the required type.
*/
@Test
public void testGetInstances() throws Exception {
Configuration conf = new Configuration();
List<SampleInterface> classes =
conf.getInstances("no.such.property", SampleInterface.class);
assertTrue(classes.isEmpty());
conf.set("empty.property", "");
classes = conf.getInstances("empty.property", SampleInterface.class);
assertTrue(classes.isEmpty());
conf.setStrings("some.classes",
SampleClass.class.getName(), AnotherClass.class.getName());
classes = conf.getInstances("some.classes", SampleInterface.class);
assertEquals(2, classes.size());
try {
conf.setStrings("some.classes",
SampleClass.class.getName(), AnotherClass.class.getName(),
String.class.getName());
conf.getInstances("some.classes", SampleInterface.class);
fail("java.lang.String does not implement SampleInterface");
} catch (RuntimeException e) {}
try {
conf.setStrings("some.classes",
SampleClass.class.getName(), AnotherClass.class.getName(),
"no.such.Class");
conf.getInstances("some.classes", SampleInterface.class);
fail("no.such.Class does not exist");
} catch (RuntimeException e) {}
}
}
|
AnotherClass
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/http/sender/InferenceInputs.java
|
{
"start": 377,
"end": 1159
}
|
class ____ {
private final boolean stream;
public InferenceInputs(boolean stream) {
this.stream = stream;
}
public static IllegalArgumentException createUnsupportedTypeException(InferenceInputs inferenceInputs, Class<?> clazz) {
return new IllegalArgumentException(
Strings.format("Unable to convert inference inputs type: [%s] to [%s]", inferenceInputs.getClass(), clazz)
);
}
public <T extends InferenceInputs> T castTo(Class<T> clazz) {
if (clazz.isInstance(this) == false) {
throw createUnsupportedTypeException(this, clazz);
}
return clazz.cast(this);
}
public boolean stream() {
return stream;
}
public abstract boolean isSingleInput();
}
|
InferenceInputs
|
java
|
quarkusio__quarkus
|
independent-projects/qute/debug/src/main/java/io/quarkus/qute/debug/agent/evaluations/ConditionalExpressionHelper.java
|
{
"start": 281,
"end": 431
}
|
class ____ converting such a string condition into a {@link TemplateNode}
* that can be evaluated in the context of a template.
* </p>
*/
public
|
allows
|
java
|
processing__processing4
|
java/src/processing/mode/java/CompletionGenerator.java
|
{
"start": 67816,
"end": 71743
}
|
class ____
// display package name in grey
String html = "<html>" + matchedClass + " : <font color=#777777>" +
matchedClass2.substring(0, d) + "</font></html>";
candidates.add(new CompletionCandidate(matchedClass, html,
matchedClass,
CompletionCandidate.PREDEF_CLASS));
}
}
}
} else {
// ==> Complex expression of type blah.blah2().doIt,etc
// Have to resolve it by carefully traversing AST of testNode
Messages.err("Complex expression " + getNodeAsString(testnode));
log("candidates empty");
ASTNode childExpr = getChildExpression(testnode);
log("Parent expression : " + getParentExpression(testnode));
log("Child expression : " + childExpr);
if (!noCompare) {
log("Original testnode " + getNodeAsString(testnode));
testnode = getParentExpression(testnode);
log("Corrected testnode " + getNodeAsString(testnode));
}
ClassMember expr =
resolveExpression3rdParty(ps, nearestNode, testnode, noCompare);
if (expr == null) {
log("Expr is null");
} else {
boolean isArray = expr.thisClass != null && expr.thisClass.isArray();
boolean isSimpleType = (expr.astNode != null) &&
expr.astNode.getNodeType() == ASTNode.SIMPLE_TYPE;
boolean isMethod = expr.method != null;
boolean staticOnly = !isMethod && !isArray && !isSimpleType;
log("Expr is " + expr);
String lookFor = (noCompare || (childExpr == null)) ?
"" : childExpr.toString();
candidates = getMembersForType(ps, expr, lookFor, noCompare, staticOnly);
}
}
return candidates;
}
public static DefaultListModel<CompletionCandidate> filterPredictions(List<CompletionCandidate> candidates) {
Messages.log("* filterPredictions");
DefaultListModel<CompletionCandidate> defListModel = new DefaultListModel<>();
if (candidates.isEmpty())
return defListModel;
// check if first & last CompCandidate are the same methods, only then show all overloaded methods
if (candidates.get(0).getElementName()
.equals(candidates.get(candidates.size() - 1).getElementName())) {
log("All CC are methods only: " + candidates.get(0).getElementName());
for (int i = 0; i < candidates.size(); i++) {
CompletionCandidate cc = candidates.get(i).withRegeneratedCompString();
candidates.set(i, cc);
defListModel.addElement(cc);
}
}
else {
boolean ignoredSome = false;
for (int i = 0; i < candidates.size(); i++) {
if(i > 0 && (candidates.get(i).getElementName()
.equals(candidates.get(i - 1).getElementName()))){
if (candidates.get(i).getType() == CompletionCandidate.LOCAL_METHOD
|| candidates.get(i).getType() == CompletionCandidate.PREDEF_METHOD) {
CompletionCandidate cc = candidates.get(i - 1);
String label = cc.getLabel();
int x = label.lastIndexOf(')');
String newLabel;
if (candidates.get(i).getType() == CompletionCandidate.PREDEF_METHOD) {
newLabel = (cc.getLabel().contains("<html>") ? "<html>" : "")
+ cc.getElementName() + "(...)" + label.substring(x + 1);
} else {
newLabel = cc.getElementName() + "(...)" + label.substring(x + 1);
}
String newCompString = cc.getElementName() + "(";
candidates.set(i - 1, cc.withLabelAndCompString(newLabel, newCompString));
ignoredSome = true;
continue;
}
}
defListModel.addElement(candidates.get(i));
}
if (ignoredSome) {
log("Some suggestions hidden");
}
}
return defListModel;
}
}
|
name
|
java
|
apache__camel
|
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/internal/ConferenceParticipantApiMethod.java
|
{
"start": 680,
"end": 3791
}
|
enum ____ implements ApiMethod {
CREATOR(
com.twilio.rest.api.v2010.account.conference.ParticipantCreator.class,
"creator",
arg("pathConferenceSid", String.class),
arg("from", com.twilio.type.Endpoint.class),
arg("to", com.twilio.type.Endpoint.class)),
CREATOR_1(
com.twilio.rest.api.v2010.account.conference.ParticipantCreator.class,
"creator",
arg("pathAccountSid", String.class),
arg("pathConferenceSid", String.class),
arg("from", com.twilio.type.Endpoint.class),
arg("to", com.twilio.type.Endpoint.class)),
DELETER(
com.twilio.rest.api.v2010.account.conference.ParticipantDeleter.class,
"deleter",
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class)),
DELETER_1(
com.twilio.rest.api.v2010.account.conference.ParticipantDeleter.class,
"deleter",
arg("pathAccountSid", String.class),
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class)),
FETCHER(
com.twilio.rest.api.v2010.account.conference.ParticipantFetcher.class,
"fetcher",
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class)),
FETCHER_1(
com.twilio.rest.api.v2010.account.conference.ParticipantFetcher.class,
"fetcher",
arg("pathAccountSid", String.class),
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class)),
READER(
com.twilio.rest.api.v2010.account.conference.ParticipantReader.class,
"reader",
arg("pathConferenceSid", String.class)),
READER_1(
com.twilio.rest.api.v2010.account.conference.ParticipantReader.class,
"reader",
arg("pathAccountSid", String.class),
arg("pathConferenceSid", String.class)),
UPDATER(
com.twilio.rest.api.v2010.account.conference.ParticipantUpdater.class,
"updater",
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class)),
UPDATER_1(
com.twilio.rest.api.v2010.account.conference.ParticipantUpdater.class,
"updater",
arg("pathAccountSid", String.class),
arg("pathConferenceSid", String.class),
arg("pathCallSid", String.class));
private final ApiMethod apiMethod;
ConferenceParticipantApiMethod(Class<?> resultType, String name, ApiMethodArg... args) {
this.apiMethod = new ApiMethodImpl(Participant.class, resultType, name, args);
}
@Override
public String getName() { return apiMethod.getName(); }
@Override
public Class<?> getResultType() { return apiMethod.getResultType(); }
@Override
public List<String> getArgNames() { return apiMethod.getArgNames(); }
@Override
public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); }
@Override
public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); }
@Override
public Method getMethod() { return apiMethod.getMethod(); }
}
|
ConferenceParticipantApiMethod
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestJobEndNotifier.java
|
{
"start": 1538,
"end": 1649
}
|
class ____ {
HttpServer2 server;
URL baseUrl;
@SuppressWarnings("serial")
public static
|
TestJobEndNotifier
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/execution/librarycache/LibraryCacheManager.java
|
{
"start": 1233,
"end": 1415
}
|
class ____, one first needs to obtain a {@link
* ClassLoaderLease} for a given {@link JobID}. At first, the {@link ClassLoaderLease} is
* unresolved. In order to obtain the user
|
loader
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointTestBase.java
|
{
"start": 35050,
"end": 35377
}
|
class ____ implements Partitioner<Long> {
@Override
public int partition(Long key, int numPartitions) {
return (int) ((withoutHeader(key) + 1) % numPartitions);
}
}
/** Distributes chunks of the size of numPartitions in a round robin fashion. */
protected static
|
ShiftingPartitioner
|
java
|
apache__camel
|
components/camel-stringtemplate/src/generated/java/org/apache/camel/component/stringtemplate/StringTemplateComponentConfigurer.java
|
{
"start": 741,
"end": 3416
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
StringTemplateComponent target = (StringTemplateComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowcontextmapall":
case "allowContextMapAll": target.setAllowContextMapAll(property(camelContext, boolean.class, value)); return true;
case "allowtemplatefromheader":
case "allowTemplateFromHeader": target.setAllowTemplateFromHeader(property(camelContext, boolean.class, value)); return true;
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "contentcache":
case "contentCache": target.setContentCache(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowcontextmapall":
case "allowContextMapAll": return boolean.class;
case "allowtemplatefromheader":
case "allowTemplateFromHeader": return boolean.class;
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "contentcache":
case "contentCache": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
StringTemplateComponent target = (StringTemplateComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowcontextmapall":
case "allowContextMapAll": return target.isAllowContextMapAll();
case "allowtemplatefromheader":
case "allowTemplateFromHeader": return target.isAllowTemplateFromHeader();
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "contentcache":
case "contentCache": return target.isContentCache();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
|
StringTemplateComponentConfigurer
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/streams/impl/MessagePassingQueue.java
|
{
"start": 17220,
"end": 19904
}
|
class ____<E> extends MessagePassingQueue<E> {
private static final AtomicLongFieldUpdater<MessagePassingQueue.SpSc<?>> WIP_UPDATER = (AtomicLongFieldUpdater<MessagePassingQueue.SpSc<?>>) (AtomicLongFieldUpdater)AtomicLongFieldUpdater.newUpdater(MessagePassingQueue.SpSc.class, "wip");
// Todo : check false sharing
private volatile long wip;
public SpSc(Predicate<E> consumer) {
this(consumer, DEFAULT_LOW_WATER_MARK, DEFAULT_HIGH_WATER_MARK);
}
public SpSc(Predicate<E> consumer, int lowWaterMark, int highWaterMark) {
super(PlatformDependent.newSpscQueue(), consumer, lowWaterMark, highWaterMark);
}
@Override
protected boolean wipCompareAndSet(long expect, long update) {
return WIP_UPDATER.compareAndSet(this, expect, update);
}
@Override
protected long wipIncrementAndGet() {
return WIP_UPDATER.incrementAndGet(this);
}
@Override
protected long wipDecrementAndGet() {
return WIP_UPDATER.decrementAndGet(this);
}
@Override
protected long wipGet() {
return WIP_UPDATER.get(this);
}
@Override
protected long wipAddAndGet(long delta) {
return WIP_UPDATER.addAndGet(this, delta);
}
}
/**
* Factory for a queue assuming distinct single consumer thread / single producer thread
*/
public static final Factory MPSC = new Factory() {
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer, int lowWaterMark, int highWaterMark) {
return new MpSc<>(consumer, lowWaterMark, highWaterMark);
}
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer) {
return new MpSc<>(consumer);
}
};
/**
* Factory for a queue assuming distinct single consumer thread / single producer thread
*/
public static final Factory SPSC = new Factory() {
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer, int lowWaterMark, int highWaterMark) {
return new SpSc<>(consumer, lowWaterMark, highWaterMark);
}
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer) {
return new SpSc<>(consumer);
}
};
/**
* Factory for a queue assuming a same single consumer thread / single producer thread
*/
public static final Factory SINGLE_THREAD = new Factory() {
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer, int lowWaterMark, int highWaterMark) {
return new SingleThread<>(consumer, lowWaterMark, highWaterMark);
}
@Override
public <T> MessagePassingQueue<T> create(Predicate<T> consumer) {
return new SingleThread<>(consumer);
}
};
}
|
SpSc
|
java
|
google__guava
|
android/guava/src/com/google/common/hash/Funnels.java
|
{
"start": 4202,
"end": 4884
}
|
enum ____ implements Funnel<Integer> {
INSTANCE;
@Override
public void funnel(Integer from, PrimitiveSink into) {
into.putInt(from);
}
@Override
public String toString() {
return "Funnels.integerFunnel()";
}
}
/**
* Returns a funnel that processes an {@code Iterable} by funneling its elements in iteration
* order with the specified funnel. No separators are added between the elements.
*
* @since 15.0
*/
public static <E extends @Nullable Object> Funnel<Iterable<? extends E>> sequentialFunnel(
Funnel<E> elementFunnel) {
return new SequentialFunnel<>(elementFunnel);
}
private static final
|
IntegerFunnel
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldExist_create_Test.java
|
{
"start": 1161,
"end": 2404
}
|
class ____ {
private TestDescription description;
@BeforeEach
public void setUp() {
description = new TestDescription("Test");
}
@Test
void should_create_error_message_for_File() {
// WHEN
String actualMessage = shouldExist(new FakeFile("xyz")).create(description, STANDARD_REPRESENTATION);
// THEN
then(actualMessage).isEqualTo("[Test] %nExpecting file:%n xyz%nto exist.".formatted());
}
@Test
void should_create_error_message_for_Path_following_symbolic_links() {
// GIVEN
final Path actual = mock(Path.class);
// WHEN
String actualMessage = shouldExist(actual).create(description, STANDARD_REPRESENTATION);
// THEN
then(actualMessage).isEqualTo("[Test] %nExpecting path:%n %s%nto exist (symbolic links were followed).".formatted(actual));
}
@Test
void should_create_error_message_for_Path_not_following_symbolic_links() {
// GIVEN
final Path actual = mock(Path.class);
// WHEN
String actualMessage = shouldExistNoFollowLinks(actual).create(description, STANDARD_REPRESENTATION);
// THEN
then(actualMessage).isEqualTo("[Test] %nExpecting path:%n %s%nto exist (symbolic links were not followed).".formatted(actual));
}
}
|
ShouldExist_create_Test
|
java
|
alibaba__nacos
|
api/src/main/java/com/alibaba/nacos/api/grpc/auto/BiRequestStreamGrpc.java
|
{
"start": 5904,
"end": 6492
}
|
class ____ extends io.grpc.stub.AbstractStub<BiRequestStreamBlockingStub> {
private BiRequestStreamBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private BiRequestStreamBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@Override
protected BiRequestStreamBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BiRequestStreamBlockingStub(channel, callOptions);
}
}
/**
*/
public static final
|
BiRequestStreamBlockingStub
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/service/ServiceRegistryTest.java
|
{
"start": 6157,
"end": 6476
}
|
class ____ implements ServiceRegistryAwareService, Configurable, Startable, Service {
@Override
public void start() {
}
@Override
public void configure(Map<String, Object> configurationValues) {
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
}
}
}
|
FakeService
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/util/FieldInfoTest.java
|
{
"start": 3409,
"end": 3662
}
|
class ____<T> {
private List<T> value;
public List<T> getValue() {
return value;
}
public void setValue(List<T> value) {
this.value = value;
}
}
public static
|
GenericListSetterEntity
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/state/ttl/TtlAwareSerializerUpgradeTest.java
|
{
"start": 4697,
"end": 7136
}
|
class ____
implements UpgradeVerifier<TtlValue<String>> {
@Override
public TypeSerializer<TtlValue<String>> createUpgradedSerializer() {
return new TtlAwareSerializer<>(
new TtlStateFactory.TtlSerializer<>(
LongSerializer.INSTANCE, StringSerializer.INSTANCE));
}
@Override
public Condition<TtlValue<String>> testDataCondition() {
return new Condition<>(
ttlValue -> Objects.equals(ttlValue.getUserValue(), TEST_DATA), "value");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<TtlValue<String>>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAfterMigration();
}
}
@Disabled
@ParameterizedTest(name = "Test Specification = {0}")
@MethodSource("createTestSpecificationsForAllVersions")
void restoreSerializerIsValid(TestSpecification<String, TtlValue<String>> testSpecification)
throws Exception {
// Restore test should be skipped for TtlMigrationTest, since the serializer value type will
// be changed during ttl migration.
}
@Override
public <T> DataInputView readAndThenWriteData(
DataInputView originalDataInput,
TypeSerializer<T> readSerializer,
TypeSerializer<T> writeSerializer,
Condition<T> testDataCondition)
throws IOException {
TtlAwareSerializer<T, ?> reader = (TtlAwareSerializer<T, ?>) readSerializer;
TtlAwareSerializer<T, ?> writer = (TtlAwareSerializer<T, ?>) writeSerializer;
DataOutputSerializer migratedOut = new DataOutputSerializer(INITIAL_OUTPUT_BUFFER_SIZE);
writer.migrateValueFromPriorSerializer(
reader,
() -> reader.deserialize(originalDataInput),
migratedOut,
TtlTimeProvider.DEFAULT);
DataInputView inputView = new DataInputDeserializer(migratedOut.wrapAsByteBuffer());
T data = writer.deserialize(inputView);
assertThat(data).is(testDataCondition);
DataOutputSerializer out = new DataOutputSerializer(INITIAL_OUTPUT_BUFFER_SIZE);
writeSerializer.serialize(data, out);
return new DataInputDeserializer(out.wrapAsByteBuffer());
}
}
|
TtlAwareSerializerEnablingTtlVerifier
|
java
|
apache__camel
|
components/camel-pubnub/src/test/java/org/apache/camel/component/pubnub/PubNubConfigurationTest.java
|
{
"start": 1186,
"end": 3060
}
|
class ____ extends CamelTestSupport {
@Test
public void createEndpointWithIllegalArguments() {
PubNubComponent component = context.getComponent("pubnub", PubNubComponent.class);
assertThrows(IllegalArgumentException.class,
() -> component.createEndpoint("pubnub"));
}
@Test
public void createEndpointWithMinimalConfiguration() throws Exception {
PubNubComponent component = context.getComponent("pubnub", PubNubComponent.class);
PubNubEndpoint endpoint = (PubNubEndpoint) component.createEndpoint("pubnub:xxx?subscribeKey=mysubkey");
assertEquals("xxx", endpoint.getConfiguration().getChannel());
assertEquals("mysubkey", endpoint.getConfiguration().getSubscribeKey());
assertTrue(endpoint.getConfiguration().isSecure());
}
@Test
public void createEndpointWithMaximalConfiguration() throws Exception {
PubNubComponent component = context.getComponent("pubnub", PubNubComponent.class);
PubNubEndpoint endpoint = (PubNubEndpoint) component
.createEndpoint(
"pubnub:xxx?subscribeKey=mysubkey&publishKey=mypubkey&secretKey=secrets&uuid=myuuid&operation=PUBLISH&secure=false&authKey=authKey");
assertEquals("xxx", endpoint.getConfiguration().getChannel());
assertEquals("mysubkey", endpoint.getConfiguration().getSubscribeKey());
assertEquals("mypubkey", endpoint.getConfiguration().getPublishKey());
assertEquals("secrets", endpoint.getConfiguration().getSecretKey());
assertEquals("myuuid", endpoint.getConfiguration().getUuid());
assertEquals("PUBLISH", endpoint.getConfiguration().getOperation());
assertEquals("authKey", endpoint.getConfiguration().getAuthKey());
assertFalse(endpoint.getConfiguration().isSecure());
}
}
|
PubNubConfigurationTest
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ser/impl/PropertySerializerMap.java
|
{
"start": 7460,
"end": 8096
}
|
class ____
{
public final Class<?> type;
public final ValueSerializer<Object> serializer;
public TypeAndSerializer(Class<?> type, ValueSerializer<Object> serializer) {
this.type = type;
this.serializer = serializer;
}
}
/*
/**********************************************************************
/* Implementations
/**********************************************************************
*/
/**
* Bogus instance that contains no serializers; used as the default
* map with new serializers.
*/
private final static
|
TypeAndSerializer
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java
|
{
"start": 17632,
"end": 17860
}
|
class ____ extends AsyncMethodBean implements SimpleInterface {
@Override
public Future<String> returnSomething2(int i) {
throw new UnsupportedOperationException();
}
}
@Async("e0")
public static
|
SimpleAsyncMethodBean
|
java
|
playframework__playframework
|
dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-multiple-databases/app/models/Group.java
|
{
"start": 180,
"end": 347
}
|
class ____ {
public final Long id;
public final String name;
public Group(Long id, String name) {
this.id = id;
this.name = name;
}
}
|
Group
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/parser/Lexer.java
|
{
"start": 100009,
"end": 105330
}
|
interface ____ {
boolean handle(Token lastToken, String comment);
}
public boolean hasComment() {
return comments != null;
}
public int getCommentCount() {
return commentCount;
}
public void skipToEOF() {
pos = text.length();
this.token = Token.EOF;
}
public boolean isEndOfComment() {
return endOfComment;
}
protected boolean isSafeComment(String comment) {
if (comment == null) {
return true;
}
comment = comment.toLowerCase();
if (comment.indexOf("select") != -1 //
|| comment.indexOf("delete") != -1 //
|| comment.indexOf("insert") != -1 //
|| comment.indexOf("update") != -1 //
|| comment.indexOf("into") != -1 //
|| comment.indexOf("where") != -1 //
|| comment.indexOf("or") != -1 //
|| comment.indexOf("and") != -1 //
|| comment.indexOf("union") != -1 //
|| comment.indexOf('\'') != -1 //
|| comment.indexOf('=') != -1 //
|| comment.indexOf('>') != -1 //
|| comment.indexOf('<') != -1 //
|| comment.indexOf('&') != -1 //
|| comment.indexOf('|') != -1 //
|| comment.indexOf('^') != -1 //
) {
return false;
}
return true;
}
protected void addComment(String comment) {
if (comments == null) {
comments = new ArrayList<String>(2);
}
comments.add(comment);
}
public final List<String> getComments() {
return comments;
}
public int getLine() {
return line;
}
public void computeRowAndColumn(SQLObject x) {
if (!keepSourceLocation) {
return;
}
int line = 1;
int column = 1;
for (int i = 0; i < startPos; ++i) {
char ch = text.charAt(i);
if (ch == '\n') {
column = 1;
line++;
} else {
column++;
}
}
x.setSource(line, column);
}
public void computeRowAndColumn() {
int line = 1;
int column = 1;
for (int i = 0; i < startPos; ++i) {
char ch = text.charAt(i);
if (ch == '\n') {
column = 1;
line++;
} else {
column++;
}
}
this.posLine = line;
this.posColumn = column;
}
public int getPosLine() {
return posLine;
}
public int getPosColumn() {
return posColumn;
}
public void config(SQLParserFeature feature, boolean state) {
features = SQLParserFeature.config(features, feature, state);
if (feature == OptimizedForParameterized) {
optimizedForParameterized = state;
} else if (feature == KeepComments) {
this.keepComments = state;
} else if (feature == KeepSourceLocation) {
this.keepSourceLocation = state;
} else if (feature == SkipComments) {
this.skipComment = state;
}
}
public TimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
public final boolean isEnabled(SQLParserFeature feature) {
return SQLParserFeature.isEnabled(this.features, feature);
}
public static String parameterize(String sql, DbType dbType) {
Lexer lexer = SQLParserUtils.createLexer(sql, dbType);
lexer.optimizedForParameterized = true; // optimized
lexer.nextToken();
StringBuilder buf = new StringBuilder();
for_:
for (; ; ) {
Token token = lexer.token;
switch (token) {
case LITERAL_ALIAS:
case LITERAL_FLOAT:
case LITERAL_CHARS:
case LITERAL_INT:
case LITERAL_NCHARS:
case LITERAL_HEX:
case VARIANT:
if (buf.length() != 0) {
buf.append(' ');
}
buf.append('?');
break;
case COMMA:
buf.append(',');
break;
case EQ:
buf.append('=');
break;
case EOF:
break for_;
case ERROR:
return sql;
case SELECT:
buf.append("SELECT");
break;
case UPDATE:
buf.append("UPDATE");
break;
default:
if (buf.length() != 0) {
buf.append(' ');
}
lexer.stringVal(buf);
break;
}
lexer.nextToken();
}
return buf.toString();
}
public String getSource() {
return text;
}
protected boolean dialectFeatureEnabled(DialectFeature.LexerFeature feature) {
return dialectFeature.isEnabled(feature);
}
}
|
CommentHandler
|
java
|
apache__flink
|
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/legacy/table/factories/StreamTableSourceFactory.java
|
{
"start": 1647,
"end": 1773
}
|
interface ____ instances of {@link DynamicTableSource}. See FLIP-95 for more information.
*/
@Deprecated
@Internal
public
|
creates
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/enrich/action/PutEnrichPolicyAction.java
|
{
"start": 873,
"end": 1408
}
|
class ____ extends ActionType<AcknowledgedResponse> {
public static final PutEnrichPolicyAction INSTANCE = new PutEnrichPolicyAction();
public static final String NAME = "cluster:admin/xpack/enrich/put";
private PutEnrichPolicyAction() {
super(NAME);
}
public static Request fromXContent(TimeValue masterNodeTimeout, XContentParser parser, String name) throws IOException {
return new Request(masterNodeTimeout, name, EnrichPolicy.fromXContent(parser));
}
public static
|
PutEnrichPolicyAction
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
|
{
"start": 21032,
"end": 21436
}
|
class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Integer> {
@Override
public TypeSerializer<Integer> createPriorSerializer() {
return IntSerializer.INSTANCE;
}
@Override
public Integer createTestData() {
return 123456;
}
}
/** IntSerializerVerifier. */
public static final
|
IntSerializerSetup
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/aggregate/OracleAggregateSupport.java
|
{
"start": 26655,
"end": 26735
}
|
enum ____ {
OSON,
MERGEPATCH,
QUERY_AND_PATH,
QUERY,
NONE
}
|
JsonSupport
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/RemoteUserAttribute.java
|
{
"start": 222,
"end": 1239
}
|
class ____ implements ExchangeAttribute {
public static final String REMOTE_USER_SHORT = "%u";
public static final String REMOTE_USER = "%{REMOTE_USER}";
public static final String VERTX_USER_NAME = "username";
public static final ExchangeAttribute INSTANCE = new RemoteUserAttribute();
private RemoteUserAttribute() {
}
@Override
public String readAttribute(final RoutingContext exchange) {
User user = exchange.user();
if (user == null) {
return null;
}
if (user instanceof QuarkusHttpUser quarkusUser) {
return quarkusUser.getSecurityIdentity().getPrincipal().getName();
} else {
return user.principal().getString(VERTX_USER_NAME);
}
}
@Override
public void writeAttribute(final RoutingContext exchange, final String newValue) throws ReadOnlyAttributeException {
throw new ReadOnlyAttributeException("Remote user", newValue);
}
public static final
|
RemoteUserAttribute
|
java
|
apache__maven
|
api/maven-api-core/src/main/java/org/apache/maven/api/services/DependencyCoordinatesFactoryRequest.java
|
{
"start": 1495,
"end": 3896
}
|
interface ____ extends ArtifactCoordinatesFactoryRequest {
String getScope();
boolean isOptional();
@Nonnull
Collection<Exclusion> getExclusions();
@Nonnull
static DependencyCoordinatesFactoryRequest build(
@Nonnull Session session,
String groupId,
String artifactId,
String version,
String classifier,
String extension,
String type) {
return DependencyCoordinatesFactoryRequest.builder()
.session(requireNonNull(session, "session cannot be null"))
.groupId(groupId)
.artifactId(artifactId)
.version(version)
.classifier(classifier)
.extension(extension)
.type(type)
.build();
}
@Nonnull
static DependencyCoordinatesFactoryRequest build(
@Nonnull Session session, @Nonnull ArtifactCoordinates coordinates) {
return builder()
.session(requireNonNull(session, "session cannot be null"))
.groupId(requireNonNull(coordinates, "coordinates cannot be null")
.getGroupId())
.artifactId(coordinates.getArtifactId())
.version(coordinates.getVersionConstraint().toString())
.classifier(coordinates.getClassifier())
.extension(coordinates.getExtension())
.build();
}
@Nonnull
static DependencyCoordinatesFactoryRequest build(@Nonnull Session session, @Nonnull Dependency dependency) {
return builder()
.session(requireNonNull(session, "session cannot be null"))
.groupId(requireNonNull(dependency, "dependency").getGroupId())
.artifactId(dependency.getArtifactId())
.version(dependency.getVersion().toString())
.classifier(dependency.getClassifier())
.extension(dependency.getExtension())
.type(dependency.getType().id())
.scope(dependency.getScope().id())
.optional(dependency.isOptional())
.build();
}
@Nonnull
static DependencyCoordinatesFactoryRequestBuilder builder() {
return new DependencyCoordinatesFactoryRequestBuilder();
}
@NotThreadSafe
|
DependencyCoordinatesFactoryRequest
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/UpperLimitExceptionParameter.java
|
{
"start": 1162,
"end": 1820
}
|
class ____ extends MessageQueryParameter<Integer> {
public static final String KEY = "maxExceptions";
public UpperLimitExceptionParameter() {
super(KEY, MessageParameter.MessageParameterRequisiteness.OPTIONAL);
}
@Override
public Integer convertStringToValue(String value) {
return Integer.valueOf(value);
}
@Override
public String convertValueToString(Integer value) {
return value.toString();
}
@Override
public String getDescription() {
return "Comma-separated list of integer values that specifies the upper limit of exceptions to return.";
}
}
|
UpperLimitExceptionParameter
|
java
|
apache__maven
|
compat/maven-model/src/test/java/org/apache/maven/model/pom/PomMemoryAnalyzer.java
|
{
"start": 2480,
"end": 12905
}
|
class ____ {
private final Map<String, Map<String, StringStats>> pathStats = new HashMap<>();
private final Map<String, Integer> globalStringFrequency = new HashMap<>();
private int totalPoms = 0;
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: PomMemoryAnalyzer <directory-with-poms>");
System.exit(1);
}
Path rootDir = Paths.get(args[0]);
PomMemoryAnalyzer analyzer = new PomMemoryAnalyzer();
MavenStaxReader reader = new MavenStaxReader();
// Find all pom.xml files, excluding those under src/ or target/
Files.walk(rootDir)
.filter(path -> path.getFileName().toString().equals("pom.xml"))
.filter(path -> !containsSrcOrTarget(path))
.forEach(pomPath -> {
try {
Model model = reader.read(Files.newInputStream(pomPath));
analyzer.analyzePom(model);
} catch (Exception e) {
System.err.println("Error processing " + pomPath + ": " + e.getMessage());
}
});
// Print analysis
analyzer.printAnalysis();
}
private static boolean containsSrcOrTarget(Path pomPath) {
Path parent = pomPath.getParent();
while (parent != null && parent.getFileName() != null) {
String dirName = parent.getFileName().toString();
if (dirName.equals("src") || dirName.equals("target")) {
return true;
}
parent = parent.getParent();
}
return false;
}
public void analyzePom(Model model) {
totalPoms++;
Set<Object> visited = new HashSet<>();
processModelNode(model, "/project", "project", visited);
}
private void processModelNode(Object node, String currentPath, String elementName, Set<Object> visited) {
if (node == null || !visited.add(node)) {
return;
}
Class<?> clazz = node.getClass();
while (clazz != null && !clazz.equals(Object.class)) {
for (Field field : clazz.getDeclaredFields()) {
// Skip static fields and synthetic fields
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
continue;
}
try {
field.setAccessible(true);
Object value = field.get(node);
if (value == null) {
continue;
}
String fullPath = currentPath + "/" + field.getName();
if (value instanceof String strValue) {
recordString(fullPath, strValue);
globalStringFrequency.merge(strValue, 1, Integer::sum);
} else if (value instanceof List<?> list) {
for (Object item : list) {
if (item != null) {
String itemName = getSingular(field.getName());
processModelNode(item, fullPath + "/" + itemName, itemName, visited);
}
}
} else if (value instanceof Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (entry.getValue() != null) {
processModelNode(
entry.getValue(),
fullPath + "/" + entry.getKey(),
entry.getKey().toString(),
visited);
}
}
} else if (!value.getClass().isPrimitive()
&& !value.getClass().getName().startsWith("java.")) {
processModelNode(value, fullPath, field.getName(), visited);
}
} catch (Exception e) {
// Skip inaccessible or problematic fields
}
}
clazz = clazz.getSuperclass();
}
}
private String getSingular(String plural) {
if (plural.endsWith("ies")) {
return plural.substring(0, plural.length() - 3) + "y";
}
if (plural.endsWith("s")) {
return plural.substring(0, plural.length() - 1);
}
return plural;
}
private void recordString(String path, String value) {
pathStats
.computeIfAbsent(path, k -> new HashMap<>())
.computeIfAbsent(value, k -> new StringStats())
.recordOccurrence(value);
}
List<PathAnalysis> getPathAnalysisSorted() {
List<PathAnalysis> analysis = new ArrayList<>();
for (Map.Entry<String, Map<String, StringStats>> entry : pathStats.entrySet()) {
String path = entry.getKey();
Map<String, StringStats> stats = entry.getValue();
long uniqueStrings = stats.size();
long totalOccurrences = stats.values().stream()
.mapToLong(StringStats::getOccurrences)
.sum();
long totalMemory = stats.entrySet().stream()
.mapToLong(e -> e.getKey().length() * e.getValue().getOccurrences() * 2L)
.sum();
long potentialSavings = stats.entrySet().stream()
.mapToLong(e -> e.getKey().length() * 2L * (e.getValue().getOccurrences() - 1))
.sum();
analysis.add(new PathAnalysis(
path,
uniqueStrings,
totalOccurrences,
totalMemory,
potentialSavings,
(double) totalOccurrences / uniqueStrings,
getMostFrequentValues(stats, 5)));
}
analysis.sort((a, b) -> Long.compare(b.potentialSavings, a.potentialSavings));
return analysis;
}
private List<ValueFrequency> getMostFrequentValues(Map<String, StringStats> stats, int limit) {
return stats.entrySet().stream()
.map(e -> new ValueFrequency(e.getKey(), e.getValue().getOccurrences()))
.sorted((a, b) -> Long.compare(b.frequency, a.frequency))
.limit(limit)
.toList();
}
public void printAnalysis() {
System.out.printf("Analyzed %d POMs%n%n", totalPoms);
// First, get all paths
List<PathAnalysis> allPaths = getPathAnalysisSorted();
// Create groups based on the final path component
Map<String, List<PathAnalysis>> groupedPaths = new HashMap<>();
Map<String, Map<String, Long>> groupValueFrequencies = new HashMap<>();
for (PathAnalysis path : allPaths) {
String finalComponent = path.path.substring(path.path.lastIndexOf('/') + 1);
// Add path to its group
groupedPaths.computeIfAbsent(finalComponent, k -> new ArrayList<>()).add(path);
// Aggregate value frequencies for the group
Map<String, Long> groupFreqs = groupValueFrequencies.computeIfAbsent(finalComponent, k -> new HashMap<>());
for (ValueFrequency vf : path.mostFrequentValues) {
groupFreqs.merge(vf.value, vf.frequency, Long::sum);
}
}
// Create final group analyses and sort them by total savings
List<GroupAnalysis> sortedGroups = groupedPaths.entrySet().stream()
.map(entry -> {
String groupName = entry.getKey();
List<PathAnalysis> paths = entry.getValue();
Map<String, Long> valueFreqs = groupValueFrequencies.get(groupName);
long totalSavings =
paths.stream().mapToLong(p -> p.potentialSavings).sum();
long totalMemory =
paths.stream().mapToLong(p -> p.totalMemory).sum();
long totalUnique = valueFreqs.size();
long totalOccurrences =
valueFreqs.values().stream().mapToLong(l -> l).sum();
List<ValueFrequency> topValues = valueFreqs.entrySet().stream()
.map(e -> new ValueFrequency(e.getKey(), e.getValue()))
.sorted((a, b) -> Long.compare(b.frequency, a.frequency))
.limit(5)
.collect(Collectors.toList());
return new GroupAnalysis(
groupName, paths, totalUnique, totalOccurrences, totalMemory, totalSavings, topValues);
})
.sorted((a, b) -> Long.compare(b.totalSavings, a.totalSavings))
.toList();
// Print each group
for (GroupAnalysis group : sortedGroups) {
System.out.printf("%nPaths ending with '%s':%n", group.name);
System.out.printf("Total potential savings: %dKB%n", group.totalSavings / 1024);
System.out.printf("Total memory: %dKB%n", group.totalMemory / 1024);
System.out.printf("Total unique values: %d%n", group.totalUnique);
System.out.printf("Total occurrences: %d%n", group.totalOccurrences);
System.out.printf("Duplication ratio: %.2f%n", (double) group.totalOccurrences / group.totalUnique);
System.out.println("\nMost frequent values across all paths:");
for (ValueFrequency v : group.mostFrequentValues) {
System.out.printf(" %-70s %d times%n", v.value, v.frequency);
}
System.out.println("\nIndividual paths:");
System.out.println("----------------------------------------");
for (PathAnalysis path : group.paths.stream()
.sorted((a, b) -> Long.compare(b.potentialSavings, a.potentialSavings))
.toList()) {
System.out.printf(
"%-90s %6dKB %6dKB%n", path.path, path.totalMemory / 1024, path.potentialSavings / 1024);
}
System.out.println();
}
}
static
|
PomMemoryAnalyzer
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/api/AssertThrowsExactlyAssertionsTests.java
|
{
"start": 1324,
"end": 8774
}
|
class ____ {
private static final Executable nix = () -> {
};
@Test
void assertThrowsExactlyTheSpecifiedExceptionClass() {
var actual = assertThrowsExactly(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
});
assertNotNull(actual);
}
@Test
void assertThrowsExactlyWithTheExpectedChildException() {
try {
assertThrowsExactly(RuntimeException.class, () -> {
throw new Exception();
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.RuntimeException>");
assertMessageContains(ex, "but was: <java.lang.Exception>");
assertThat(ex).hasCauseExactlyInstanceOf(Exception.class);
}
}
@Test
void assertThrowsExactlyWithTheExpectedParentException() {
try {
assertThrowsExactly(RuntimeException.class, () -> {
throw new NumberFormatException();
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.RuntimeException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseExactlyInstanceOf(NumberFormatException.class);
}
}
@Test
void assertThrowsWithMethodReferenceForNonVoidReturnType() {
FutureTask<String> future = new FutureTask<>(() -> {
throw new RuntimeException("boom");
});
future.run();
ExecutionException exception = assertThrowsExactly(ExecutionException.class, future::get);
assertNotNull(exception.getCause());
assertEquals("boom", exception.getCause().getMessage());
}
@Test
void assertThrowsWithMethodReferenceForVoidReturnType() {
var object = new Object();
IllegalMonitorStateException exception;
exception = assertThrowsExactly(IllegalMonitorStateException.class, object::notify);
assertNotNull(exception);
// Note that Object.wait(...) is an overloaded method with a void return type
exception = assertThrowsExactly(IllegalMonitorStateException.class, object::wait);
assertNotNull(exception);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowable() {
EnigmaThrowable enigmaThrowable = assertThrowsExactly(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
});
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowableWithMessage() {
EnigmaThrowable enigmaThrowable = assertThrowsExactly(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
}, "message");
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowableWithMessageSupplier() {
EnigmaThrowable enigmaThrowable = assertThrowsExactly(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
}, () -> "message");
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsCheckedException() {
IOException exception = assertThrowsExactly(IOException.class, () -> {
throw new IOException();
});
assertNotNull(exception);
}
@Test
void assertThrowsWithExecutableThatThrowsRuntimeException() {
IllegalStateException illegalStateException = assertThrowsExactly(IllegalStateException.class, () -> {
throw new IllegalStateException();
});
assertNotNull(illegalStateException);
}
@Test
void assertThrowsWithExecutableThatThrowsError() {
StackOverflowError stackOverflowError = assertThrowsExactly(StackOverflowError.class,
AssertionTestUtils::recurseIndefinitely);
assertNotNull(stackOverflowError);
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnException() {
try {
assertThrowsExactly(IllegalStateException.class, nix);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "Expected java.lang.IllegalStateException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageString() {
try {
assertThrowsExactly(IOException.class, nix, "Custom message");
expectAssertionFailedError();
}
catch (AssertionError ex) {
assertMessageEquals(ex,
"Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageSupplier() {
try {
assertThrowsExactly(IOException.class, nix, () -> "Custom message");
expectAssertionFailedError();
}
catch (AssertionError ex) {
assertMessageEquals(ex,
"Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedException() {
try {
assertThrowsExactly(IllegalStateException.class, () -> {
throw new NumberFormatException();
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseExactlyInstanceOf(NumberFormatException.class);
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageString() {
try {
assertThrowsExactly(IllegalStateException.class, () -> {
throw new NumberFormatException();
}, "Custom message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
// Should look something like this:
// Custom message ==> Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>
assertMessageStartsWith(ex, "Custom message ==> ");
assertMessageContains(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseExactlyInstanceOf(NumberFormatException.class);
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageSupplier() {
try {
assertThrowsExactly(IllegalStateException.class, () -> {
throw new NumberFormatException();
}, () -> "Custom message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
// Should look something like this:
// Custom message ==> Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>
assertMessageStartsWith(ex, "Custom message ==> ");
assertMessageContains(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseExactlyInstanceOf(NumberFormatException.class);
}
}
@Test
@SuppressWarnings("serial")
void assertThrowsWithExecutableThatThrowsInstanceOfAnonymousInnerClassAsUnexpectedException() {
try {
assertThrowsExactly(IllegalStateException.class, () -> {
throw new NumberFormatException() {
};
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
// As of the time of this writing, the
|
AssertThrowsExactlyAssertionsTests
|
java
|
apache__camel
|
components/camel-salesforce/camel-salesforce-codegen/src/main/java/org/apache/camel/component/salesforce/codegen/GeneratePubSubExecution.java
|
{
"start": 1084,
"end": 2123
}
|
class ____ extends AbstractSalesforceExecution {
private String[] topics;
private File outputDirectory;
@Override
protected void executeWithClient() throws Exception {
for (String topicName : topics) {
final TopicInfo topicInfo = getPubSubApiClient().getTopicInfo(topicName);
final String schemaJson = getPubSubApiClient().getSchemaJson(topicInfo.getSchemaId());
final File schemaFile = File.createTempFile("schema", ".json", outputDirectory);
schemaFile.deleteOnExit();
Files.writeString(schemaFile.toPath(), schemaJson);
SpecificCompiler.compileSchema(schemaFile, outputDirectory);
}
}
public void setTopics(String[] topics) {
this.topics = topics;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
@Override
protected Logger getLog() {
return LoggerFactory.getLogger(GeneratePubSubExecution.class);
}
}
|
GeneratePubSubExecution
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/aot/generate/GeneratedClasses.java
|
{
"start": 6513,
"end": 8141
}
|
class ____ the specified {@code featureName} targeting
* the specified {@code component}.
* @param featureName the name of the feature to associate with the
* generated class
* @param targetComponent the target component
* @param type a {@link Consumer} used to build the type
* @return the newly generated class
*/
public GeneratedClass addForFeatureComponent(String featureName,
Class<?> targetComponent, Consumer<TypeSpec.Builder> type) {
return addForFeatureComponent(featureName, ClassName.get(targetComponent), type);
}
private GeneratedClass createAndAddGeneratedClass(String featureName,
@Nullable ClassName targetComponent, Consumer<TypeSpec.Builder> type) {
ClassName className = this.classNameGenerator.generateClassName(featureName, targetComponent);
GeneratedClass generatedClass = new GeneratedClass(className, type);
this.classes.add(generatedClass);
return generatedClass;
}
/**
* Write the {@link GeneratedClass generated classes} using the given
* {@link GeneratedFiles} instance.
* @param generatedFiles where to write the generated classes
*/
void writeTo(GeneratedFiles generatedFiles) {
Assert.notNull(generatedFiles, "'generatedFiles' must not be null");
List<GeneratedClass> generatedClasses = new ArrayList<>(this.classes);
generatedClasses.sort(Comparator.comparing(GeneratedClass::getName));
for (GeneratedClass generatedClass : generatedClasses) {
generatedFiles.addSourceFile(generatedClass.generateJavaFile());
}
}
/**
* Create a new {@link GeneratedClasses} instance using the specified feature
* name prefix to qualify generated
|
for
|
java
|
netty__netty
|
transport/src/test/java/io/netty/channel/local/LocalTransportThreadModelTest.java
|
{
"start": 22262,
"end": 23676
}
|
class ____ extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private volatile int inCnt;
private volatile int outCnt;
private volatile Thread t;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Thread t = this.t;
if (t == null) {
this.t = Thread.currentThread();
} else {
assertSame(t, Thread.currentThread());
}
int actual = (Integer) msg;
int expected = inCnt ++;
assertEquals(expected, actual);
}
@Override
public void write(
ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
assertSame(t, Thread.currentThread());
int actual = (Integer) msg;
int expected = outCnt ++;
assertEquals(expected, actual);
ctx.write(msg, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
//System.err.print("[" + Thread.currentThread().getName() + "] ");
//cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
}
|
MessageDiscarder
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/record/UnalignedMemoryRecords.java
|
{
"start": 1117,
"end": 2143
}
|
class ____ implements UnalignedRecords {
private static final UnalignedMemoryRecords EMPTY = new UnalignedMemoryRecords(ByteBuffer.allocate(0));
private final ByteBuffer buffer;
public UnalignedMemoryRecords(ByteBuffer buffer) {
this.buffer = Objects.requireNonNull(buffer);
}
public ByteBuffer buffer() {
return buffer.duplicate();
}
@Override
public int sizeInBytes() {
return buffer.remaining();
}
@Override
public int writeTo(TransferableChannel channel, int position, int length) throws IOException {
if (((long) position) + length > buffer.limit())
throw new IllegalArgumentException("position+length should not be greater than buffer.limit(), position: "
+ position + ", length: " + length + ", buffer.limit(): " + buffer.limit());
return Utils.tryWriteTo(channel, position, length, buffer);
}
public static UnalignedMemoryRecords empty() {
return EMPTY;
}
}
|
UnalignedMemoryRecords
|
java
|
apache__flink
|
flink-table/flink-sql-parser/src/main/java/org/apache/calcite/sql/SqlExplicitModelOperator.java
|
{
"start": 1305,
"end": 2399
}
|
class ____ extends SqlPrefixOperator {
public SqlExplicitModelOperator(int prec) {
super("MODEL", SqlKind.OTHER_FUNCTION, prec, null, null, null);
}
@Override
public SqlCall createCall(
@Nullable SqlLiteral functionQualifier,
SqlParserPos pos,
@Nullable SqlNode... operands) {
pos = pos.plusAll(operands);
return new SqlExplicitModelCall(
this, ImmutableNullableList.copyOf(operands), pos, functionQualifier);
}
@Override
public void validateCall(
SqlCall call,
SqlValidator validator,
SqlValidatorScope scope,
SqlValidatorScope operandScope) {
throw SqlUtil.newContextException(
call.pos, RESOURCE.objectNotFound(call.operand(0).toString()));
}
@Override
public RelDataType deriveType(SqlValidator validator, SqlValidatorScope scope, SqlCall call) {
throw SqlUtil.newContextException(
call.pos, RESOURCE.objectNotFound(call.operand(0).toString()));
}
}
|
SqlExplicitModelOperator
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/testsupport/TestObserverExTest.java
|
{
"start": 1498,
"end": 37363
}
|
class ____ extends RxJavaTest {
@Test
public void assertTestObserverEx() {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
oi.subscribe(subscriber);
subscriber.assertValues(1, 2);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
}
@Test
public void assertNotMatchCount() {
assertThrows(AssertionError.class, () -> {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
oi.subscribe(subscriber);
subscriber.assertValue(1);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
});
}
@Test
public void assertNotMatchValue() {
assertThrows(AssertionError.class, () -> {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
oi.subscribe(subscriber);
subscriber.assertValues(1, 3);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
});
}
@Test
public void assertNeverAtNotMatchingValue() {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
oi.subscribe(subscriber);
subscriber.assertNever(3);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
}
@Test
public void assertNeverAtMatchingValue() {
assertThrows(AssertionError.class, () -> {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
oi.subscribe(subscriber);
subscriber.assertValues(1, 2);
subscriber.assertNever(2);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
});
}
@Test
public void assertNeverAtMatchingPredicate() {
assertThrows(AssertionError.class, () -> {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1, 2).subscribe(to);
to.assertValues(1, 2);
to.assertNever(new Predicate<Integer>() {
@Override
public boolean test(final Integer o) throws Exception {
return o == 1;
}
});
});
}
@Test
public void assertNeverAtNotMatchingPredicate() {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(2, 3).subscribe(to);
to.assertNever(new Predicate<Integer>() {
@Override
public boolean test(final Integer o) throws Exception {
return o == 1;
}
});
}
@Test
public void assertTerminalEventNotReceived() {
assertThrows(AssertionError.class, () -> {
PublishSubject<Integer> p = PublishSubject.create();
TestObserverEx<Integer> subscriber = new TestObserverEx<>();
p.subscribe(subscriber);
p.onNext(1);
p.onNext(2);
subscriber.assertValues(1, 2);
subscriber.assertValueCount(2);
subscriber.assertTerminated();
});
}
@Test
public void wrappingMock() {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2));
Observer<Integer> mockSubscriber = TestHelper.mockObserver();
oi.subscribe(new TestObserverEx<>(mockSubscriber));
InOrder inOrder = inOrder(mockSubscriber);
inOrder.verify(mockSubscriber, times(1)).onNext(1);
inOrder.verify(mockSubscriber, times(1)).onNext(2);
inOrder.verify(mockSubscriber, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void wrappingMockWhenUnsubscribeInvolved() {
Observable<Integer> oi = Observable.fromIterable(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)).take(2);
Observer<Integer> mockSubscriber = TestHelper.mockObserver();
oi.subscribe(new TestObserverEx<>(mockSubscriber));
InOrder inOrder = inOrder(mockSubscriber);
inOrder.verify(mockSubscriber, times(1)).onNext(1);
inOrder.verify(mockSubscriber, times(1)).onNext(2);
inOrder.verify(mockSubscriber, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void errorSwallowed() {
Observable.error(new RuntimeException()).subscribe(new TestObserverEx<>());
}
@Test
public void nullExpected() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onNext(1);
try {
to.assertValue((Integer) null);
} catch (AssertionError ex) {
// this is expected
return;
}
fail("Null element check assertion didn't happen!");
}
@Test
public void nullActual() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onNext(null);
try {
to.assertValue(1);
} catch (AssertionError ex) {
// this is expected
return;
}
fail("Null element check assertion didn't happen!");
}
@Test
public void terminalErrorOnce() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onError(new TestException());
to.onError(new TestException());
try {
to.assertTerminated();
} catch (AssertionError ex) {
// this is expected
return;
}
fail("Failed to report multiple onError terminal events!");
}
@Test
public void terminalCompletedOnce() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onComplete();
to.onComplete();
try {
to.assertTerminated();
} catch (AssertionError ex) {
// this is expected
return;
}
fail("Failed to report multiple onComplete terminal events!");
}
@Test
public void terminalOneKind() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onError(new TestException());
to.onComplete();
try {
to.assertTerminated();
} catch (AssertionError ex) {
// this is expected
return;
}
fail("Failed to report multiple kinds of events!");
}
@Test
public void createDelegate() {
TestObserverEx<Integer> to1 = new TestObserverEx<>();
TestObserverEx<Integer> to = new TestObserverEx<>(to1);
to.assertNotSubscribed();
assertFalse(to.hasSubscription());
to.onSubscribe(Disposable.empty());
try {
to.assertNotSubscribed();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
assertTrue(to.hasSubscription());
assertFalse(to.isDisposed());
to.onNext(1);
to.onError(new TestException());
to.onComplete();
to1.assertValue(1).assertError(TestException.class).assertComplete();
to.dispose();
assertTrue(to.isDisposed());
assertSame(Thread.currentThread(), to.lastThread());
try {
to.assertNoValues();
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertValueCount(0);
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
to.assertValueSequence(Collections.singletonList(1));
try {
to.assertValueSequence(Collections.singletonList(2));
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
}
@Test
public void assertError() {
TestObserverEx<Integer> to = new TestObserverEx<>();
try {
to.assertError(TestException.class);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertError(new TestException());
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertError(Functions.<Throwable>alwaysTrue());
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertErrorMessage("");
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertSubscribed();
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertTerminated();
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
to.onSubscribe(Disposable.empty());
to.assertSubscribed();
to.assertNoErrors();
TestException ex = new TestException("Forced failure");
to.onError(ex);
to.assertError(ex);
to.assertError(TestException.class);
to.assertError(Functions.<Throwable>alwaysTrue());
to.assertError(new Predicate<Throwable>() {
@Override
public boolean test(Throwable t) throws Exception {
return t.getMessage() != null && t.getMessage().contains("Forced");
}
});
to.assertErrorMessage("Forced failure");
try {
to.assertErrorMessage("");
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertError(new RuntimeException());
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertError(IOException.class);
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertError(Functions.<Throwable>alwaysFalse());
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
try {
to.assertNoErrors();
throw new RuntimeException("Should have thrown");
} catch (AssertionError exc) {
// expected
}
to.assertTerminated();
to.assertValueCount(0);
to.assertNoValues();
}
@Test
public void emptyObserverEnum() {
assertEquals(1, TestObserverEx.EmptyObserver.values().length);
assertNotNull(TestObserverEx.EmptyObserver.valueOf("INSTANCE"));
}
@Test
public void valueAndClass() {
assertEquals("null", TestObserver.valueAndClass(null));
assertEquals("1 (class: Integer)", TestObserver.valueAndClass(1));
}
@Test
public void assertFailure() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onError(new TestException("Forced failure"));
to.assertFailure(TestException.class);
to.assertFailure(Functions.<Throwable>alwaysTrue());
to.assertFailureAndMessage(TestException.class, "Forced failure");
to.onNext(1);
to.assertFailure(TestException.class, 1);
to.assertFailure(Functions.<Throwable>alwaysTrue(), 1);
to.assertFailureAndMessage(TestException.class, "Forced failure", 1);
}
@Test
public void assertFuseable() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertNotFuseable();
try {
to.assertFuseable();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertFusionMode(QueueFuseable.SYNC);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.ANY);
to.onSubscribe(new ScalarDisposable<>(to, 1));
to.assertFuseable();
to.assertFusionMode(QueueFuseable.SYNC);
try {
to.assertFusionMode(QueueFuseable.NONE);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertNotFuseable();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void assertTerminated() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.assertNotTerminated();
to.onError(null);
try {
to.assertNotTerminated();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void assertResult() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onComplete();
to.assertResult();
try {
to.assertResult(1);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
to.onNext(1);
to.assertResult(1);
try {
to.assertResult(2);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertResult();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void await() throws Exception {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
assertFalse(to.await(100, TimeUnit.MILLISECONDS));
to.awaitDone(100, TimeUnit.MILLISECONDS);
assertTrue(to.isDisposed());
to.assertNotTerminated();
to.onComplete();
assertTrue(to.await(100, TimeUnit.MILLISECONDS));
to.await();
to.awaitDone(5, TimeUnit.SECONDS);
to.assertNoErrors().assertComplete();
final TestObserverEx<Integer> to1 = new TestObserverEx<>();
to1.onSubscribe(Disposable.empty());
Schedulers.single().scheduleDirect(new Runnable() {
@Override
public void run() {
to1.onComplete();
}
}, 200, TimeUnit.MILLISECONDS);
to1.await();
}
@Test
public void errors() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
assertEquals(0, to.errors().size());
to.onError(new TestException());
assertEquals(1, to.errors().size());
TestHelper.assertError(to.errors(), 0, TestException.class);
}
@Test
public void onNext() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertValueCount(0);
assertEquals(Collections.emptyList(), to.values());
to.onNext(1);
assertEquals(Collections.singletonList(1), to.values());
to.dispose();
assertTrue(to.isDisposed());
to.assertValue(1);
to.onComplete();
}
@Test
public void fusionModeToString() {
assertEquals("NONE", TestObserverEx.fusionModeToString(QueueFuseable.NONE));
assertEquals("SYNC", TestObserverEx.fusionModeToString(QueueFuseable.SYNC));
assertEquals("ASYNC", TestObserverEx.fusionModeToString(QueueFuseable.ASYNC));
assertEquals("Unknown(100)", TestObserverEx.fusionModeToString(100));
}
@Test
public void multipleTerminals() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertNotComplete();
to.onComplete();
try {
to.assertNotComplete();
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
to.assertTerminated();
to.onComplete();
try {
to.assertComplete();
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
try {
to.assertTerminated();
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
try {
to.assertNotComplete();
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
}
@Test
public void assertValue() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
try {
to.assertValue(1);
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
to.onNext(1);
to.assertValue(1);
try {
to.assertValue(2);
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
to.onNext(2);
try {
to.assertValue(1);
throw new RuntimeException("Should have thrown");
} catch (Throwable ex) {
// expected
}
}
@Test
public void onNextMisbehave() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onNext(1);
to.assertError(IllegalStateException.class);
to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onNext(null);
to.assertFailure(NullPointerException.class, (Integer)null);
}
@Test
public void assertTerminated2() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertNotTerminated();
to.onError(new TestException());
to.assertTerminated();
to.onError(new IOException());
try {
to.assertTerminated();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
try {
to.assertError(TestException.class);
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onError(new TestException());
to.onComplete();
try {
to.assertTerminated();
throw new RuntimeException("Should have thrown");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void onSubscribe() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(null);
to.assertError(NullPointerException.class);
to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
Disposable d1 = Disposable.empty();
to.onSubscribe(d1);
assertTrue(d1.isDisposed());
to.assertError(IllegalStateException.class);
to = new TestObserverEx<>();
to.dispose();
d1 = Disposable.empty();
to.onSubscribe(d1);
assertTrue(d1.isDisposed());
}
@Test
public void assertValueSequence() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onNext(1);
to.onNext(2);
try {
to.assertValueSequence(Collections.<Integer>emptyList());
throw new RuntimeException("Should have thrown");
} catch (AssertionError expected) {
assertTrue(expected.getMessage(), expected.getMessage().startsWith("More values received than expected (0)"));
}
try {
to.assertValueSequence(Collections.singletonList(1));
throw new RuntimeException("Should have thrown");
} catch (AssertionError expected) {
assertTrue(expected.getMessage(), expected.getMessage().startsWith("More values received than expected (1)"));
}
to.assertValueSequence(Arrays.asList(1, 2));
try {
to.assertValueSequence(Arrays.asList(1, 2, 3));
throw new RuntimeException("Should have thrown");
} catch (AssertionError expected) {
assertTrue(expected.getMessage(), expected.getMessage().startsWith("Fewer values received than expected (2)"));
}
}
@Test
public void assertEmpty() {
TestObserverEx<Integer> to = new TestObserverEx<>();
try {
to.assertEmpty();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
to.onSubscribe(Disposable.empty());
to.assertEmpty();
to.onNext(1);
try {
to.assertEmpty();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void awaitDoneTimed() {
TestObserverEx<Integer> to = new TestObserverEx<>();
Thread.currentThread().interrupt();
try {
to.awaitDone(5, TimeUnit.SECONDS);
} catch (RuntimeException ex) {
assertTrue(ex.toString(), ex.getCause() instanceof InterruptedException);
}
}
@Test
public void assertNotSubscribed() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.assertNotSubscribed();
to.errors().add(new TestException());
try {
to.assertNotSubscribed();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void assertErrorMultiple() {
TestObserverEx<Integer> to = new TestObserverEx<>();
TestException e = new TestException();
to.errors().add(e);
to.errors().add(new TestException());
try {
to.assertError(TestException.class);
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
try {
to.assertError(e);
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
try {
to.assertError(Functions.<Throwable>alwaysTrue());
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
try {
to.assertErrorMessage("");
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void errorInPredicate() {
TestObserverEx<Object> to = new TestObserverEx<>();
to.onError(new RuntimeException());
try {
to.assertError(new Predicate<Throwable>() {
@Override
public boolean test(Throwable throwable) throws Exception {
throw new TestException();
}
});
} catch (TestException ex) {
// expected
return;
}
fail("Error in predicate but not thrown!");
}
@Test
public void assertComplete() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
try {
to.assertComplete();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
to.onComplete();
to.assertComplete();
to.onComplete();
try {
to.assertComplete();
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
// expected
}
}
@Test
public void completeWithoutOnSubscribe() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onComplete();
to.assertError(IllegalStateException.class);
}
@Test
public void completeDelegateThrows() {
TestObserverEx<Integer> to = new TestObserverEx<>(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer value) {
}
@Override
public void onError(Throwable e) {
throw new TestException();
}
@Override
public void onComplete() {
throw new TestException();
}
});
to.onSubscribe(Disposable.empty());
try {
to.onComplete();
throw new RuntimeException("Should have thrown!");
} catch (TestException ex) {
to.assertTerminated();
}
}
@Test
public void errorDelegateThrows() {
TestObserverEx<Integer> to = new TestObserverEx<>(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer value) {
}
@Override
public void onError(Throwable e) {
throw new TestException();
}
@Override
public void onComplete() {
throw new TestException();
}
});
to.onSubscribe(Disposable.empty());
try {
to.onError(new IOException());
throw new RuntimeException("Should have thrown!");
} catch (TestException ex) {
to.assertTerminated();
}
}
@Test
public void syncQueueThrows() {
TestObserverEx<Object> to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.SYNC);
Observable.range(1, 5)
.map(new Function<Integer, Object>() {
@Override
public Object apply(Integer v) throws Exception { throw new TestException(); }
})
.subscribe(to);
to.assertSubscribed()
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertFailure(TestException.class);
}
@Test
public void asyncQueueThrows() {
TestObserverEx<Object> to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.ANY);
UnicastSubject<Integer> us = UnicastSubject.create();
us
.map(new Function<Integer, Object>() {
@Override
public Object apply(Integer v) throws Exception { throw new TestException(); }
})
.subscribe(to);
us.onNext(1);
to.assertSubscribed()
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertFailure(TestException.class);
}
@Test
public void completedMeansDisposed() {
// 2.0.2 - a terminated TestObserver no longer reports isDisposed
assertFalse(Observable.just(1)
.test()
.assertResult(1).isDisposed());
}
@Test
public void errorMeansDisposed() {
// 2.0.2 - a terminated TestObserver no longer reports isDisposed
assertFalse(Observable.error(new TestException())
.test()
.assertFailure(TestException.class).isDisposed());
}
@Test
public void asyncFusion() {
TestObserverEx<Object> to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.ANY);
UnicastSubject<Integer> us = UnicastSubject.create();
us
.subscribe(to);
us.onNext(1);
us.onComplete();
to.assertSubscribed()
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(1);
}
@Test
public void assertValuePredicateEmpty() {
assertThrows("No values", AssertionError.class, () -> {
TestObserverEx<Object> to = new TestObserverEx<>();
Observable.empty().subscribe(to);
to.assertValue(new Predicate<Object>() {
@Override public boolean test(final Object o) throws Exception {
return false;
}
});
});
}
@Test
public void assertValuePredicateMatch() {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1).subscribe(to);
to.assertValue(new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o == 1;
}
});
}
@Test
public void assertValuePredicateNoMatch() {
assertThrows("Value not present", AssertionError.class, () -> {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1).subscribe(to);
to.assertValue(new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o != 1;
}
});
});
}
@Test
public void assertValuePredicateMatchButMore() {
assertThrows("Value present but other values as well", AssertionError.class, () -> {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1, 2).subscribe(to);
to.assertValue(new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o == 1;
}
});
});
}
@Test
public void assertValueAtPredicateEmpty() {
assertThrows("No values", AssertionError.class, () -> {
TestObserverEx<Object> to = new TestObserverEx<>();
Observable.empty().subscribe(to);
to.assertValueAt(0, new Predicate<Object>() {
@Override public boolean test(final Object o) throws Exception {
return false;
}
});
});
}
@Test
public void assertValueAtPredicateMatch() {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1, 2).subscribe(to);
to.assertValueAt(1, new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o == 2;
}
});
}
@Test
public void assertValueAtPredicateNoMatch() {
assertThrows("Value not present", AssertionError.class, () -> {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1, 2, 3).subscribe(to);
to.assertValueAt(2, new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o != 3;
}
});
});
}
@Test
public void assertValueAtInvalidIndex() {
assertThrows("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
TestObserverEx<Integer> to = new TestObserverEx<>();
Observable.just(1, 2).subscribe(to);
to.assertValueAt(2, new Predicate<Integer>() {
@Override public boolean test(final Integer o) throws Exception {
return o == 1;
}
});
});
}
@Test
public void assertValueAtIndexEmpty() {
assertThrows("No values", AssertionError.class, () -> {
TestObserverEx<Object> to = new TestObserverEx<>();
Observable.empty().subscribe(to);
to.assertValueAt(0, "a");
});
}
@Test
public void assertValueAtIndexMatch() {
TestObserverEx<String> to = new TestObserverEx<>();
Observable.just("a", "b").subscribe(to);
to.assertValueAt(1, "b");
}
@Test
public void assertValueAtIndexNoMatch() {
assertThrows("\nexpected: b (class: String)\ngot: c (class: String) (latch = 0, values = 3, errors = 0, completions = 1)", AssertionError.class, () -> {
TestObserverEx<String> to = new TestObserverEx<>();
Observable.just("a", "b", "c").subscribe(to);
to.assertValueAt(2, "b");
});
}
@Test
public void assertValueAtIndexInvalidIndex() {
assertThrows("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
TestObserverEx<String> to = new TestObserverEx<>();
Observable.just("a", "b").subscribe(to);
to.assertValueAt(2, "c");
});
}
@Test
public void withTag() {
try {
for (int i = 1; i < 3; i++) {
Observable.just(i)
.test()
.withTag("testing with item=" + i)
.assertResult(1)
;
}
throw new RuntimeException("Should have thrown!");
} catch (AssertionError ex) {
assertTrue(ex.toString(), ex.toString().contains("testing with item=2"));
}
}
@Test
public void assertValuesOnly() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertValuesOnly();
to.onNext(5);
to.assertValuesOnly(5);
to.onNext(-1);
to.assertValuesOnly(5, -1);
}
@Test
public void assertValuesOnlyThrowsOnUnexpectedValue() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.assertValuesOnly();
to.onNext(5);
to.assertValuesOnly(5);
to.onNext(-1);
try {
to.assertValuesOnly(5);
throw new RuntimeException();
} catch (AssertionError ex) {
// expected
}
}
@Test
public void assertValuesOnlyThrowsWhenCompleted() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onComplete();
try {
to.assertValuesOnly();
throw new RuntimeException();
} catch (AssertionError ex) {
// expected
}
}
@Test
public void assertValuesOnlyThrowsWhenErrored() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.onSubscribe(Disposable.empty());
to.onError(new TestException());
try {
to.assertValuesOnly();
throw new RuntimeException();
} catch (AssertionError ex) {
// expected
}
}
}
|
TestObserverExTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/engine/Engine.java
|
{
"start": 72820,
"end": 73031
}
|
interface ____ {
/**
* Called when a fatal exception occurred
*/
default void onFailedEngine(String reason, @Nullable Exception e) {}
}
public abstract static
|
EventListener
|
java
|
jhy__jsoup
|
src/test/java/org/jsoup/nodes/ElementTest.java
|
{
"start": 1375,
"end": 52377
}
|
class ____ {
private final String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>";
private static void validateScriptContents(String src, Element el) {
assertEquals("", el.text()); // it's not text
assertEquals("", el.ownText());
assertEquals("", el.wholeText());
assertEquals(src, el.html());
assertEquals(src, el.data());
}
private static void validateXmlScriptContents(Element el) {
assertEquals("var foo = 5 < 2; var bar = 1 && 2;", el.text());
assertEquals("var foo = 5 < 2; var bar = 1 && 2;", el.ownText());
assertEquals("var foo = 5 < 2;\nvar bar = 1 && 2;", el.wholeText());
assertEquals("var foo = 5 < 2;\nvar bar = 1 && 2;", el.html());
assertEquals("", el.data());
}
@Test
public void testId() {
Document doc = Jsoup.parse("<div id=Foo>");
Element el = doc.selectFirst("div");
assertEquals("Foo", el.id());
}
@Test
public void testSetId() {
Document doc = Jsoup.parse("<div id=Boo>");
Element el = doc.selectFirst("div");
el.id("Foo");
assertEquals("Foo", el.id());
}
@Test
public void getElementsByTagName() {
Document doc = Jsoup.parse(reference);
List<Element> divs = doc.getElementsByTag("div");
assertEquals(2, divs.size());
assertEquals("div1", divs.get(0).id());
assertEquals("div2", divs.get(1).id());
List<Element> ps = doc.getElementsByTag("p");
assertEquals(2, ps.size());
assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText());
assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText());
List<Element> ps2 = doc.getElementsByTag("P");
assertEquals(ps, ps2);
List<Element> imgs = doc.getElementsByTag("img");
assertEquals("foo.png", imgs.get(0).attr("src"));
List<Element> empty = doc.getElementsByTag("wtf");
assertEquals(0, empty.size());
}
@Test
public void getNamespacedElementsByTag() {
Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>");
Elements els = doc.getElementsByTag("abc:def");
assertEquals(1, els.size());
assertEquals("1", els.first().id());
assertEquals("abc:def", els.first().tagName());
}
@Test
public void testGetElementById() {
Document doc = Jsoup.parse(reference);
Element div = doc.getElementById("div1");
assertEquals("div1", div.id());
assertNull(doc.getElementById("none"));
Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>");
Element div2 = doc2.getElementById("2");
assertEquals("div", div2.tagName()); // not the span
Element span = div2.child(0).getElementById("2"); // called from <p> context should be span
assertEquals("span", span.tagName());
}
@Test
public void testGetText() {
Document doc = Jsoup.parse(reference);
assertEquals("Hello Another element", doc.text());
assertEquals("Another element", doc.getElementsByTag("p").get(1).text());
}
@Test
public void testGetChildText() {
Document doc = Jsoup.parse("<p>Hello <b>there</b> now");
Element p = doc.select("p").first();
assertEquals("Hello there now", p.text());
assertEquals("Hello now", p.ownText());
}
@Test
public void testNormalisesText() {
String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text.";
Document doc = Jsoup.parse(h);
String text = doc.text();
assertEquals("Hello There. Here is some text.", text);
}
@Test
public void testKeepsPreText() {
String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>";
Document doc = Jsoup.parse(h);
assertEquals("Hello there. What's \n\n that?", doc.text());
}
@Test
public void testKeepsPreTextInCode() {
String h = "<pre><code>code\n\ncode</code></pre>";
Document doc = Jsoup.parse(h);
assertEquals("code\n\ncode", doc.text());
assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html());
}
@Test
public void testKeepsPreTextAtDepth() {
String h = "<pre><code><span><b>code\n\ncode</b></span></code></pre>";
Document doc = Jsoup.parse(h);
assertEquals("code\n\ncode", doc.text());
assertEquals("<pre><code><span><b>code\n\ncode</b></span></code></pre>", doc.body().html());
}
@Test void doesNotWrapBlocksInPre() {
// https://github.com/jhy/jsoup/issues/1891
String h = "<pre><span><foo><div>TEST\n TEST</div></foo></span></pre>";
Document doc = Jsoup.parse(h);
assertEquals("TEST\n TEST", doc.wholeText());
assertEquals(h, doc.body().html());
}
@Test
public void testBrHasSpace() {
Document doc = Jsoup.parse("<p>Hello<br>there</p>");
assertEquals("Hello there", doc.text());
assertEquals("Hello there", doc.select("p").first().ownText());
doc = Jsoup.parse("<p>Hello <br> there</p>");
assertEquals("Hello there", doc.text());
}
@Test
public void testBrHasSpaceCaseSensitive() {
Document doc = Jsoup.parse("<p>Hello<br>there<BR>now</p>", Parser.htmlParser().settings(ParseSettings.preserveCase));
assertEquals("Hello there now", doc.text());
assertEquals("Hello there now", doc.select("p").first().ownText());
doc = Jsoup.parse("<p>Hello <br> there <BR> now</p>");
assertEquals("Hello there now", doc.text());
}
@Test public void textHasSpacesAfterBlock() {
Document doc = Jsoup.parse("<div>One</div><div>Two</div><span>Three</span><p>Fou<i>r</i></p>");
String text = doc.text();
String wholeText = doc.wholeText();
assertEquals("One Two Three Four", text);
assertEquals("OneTwoThreeFour",wholeText);
assertEquals("OneTwo",Jsoup.parse("<span>One</span><span>Two</span>").text());
}
@Test
public void testWholeText() {
Document doc = Jsoup.parse("<p> Hello\nthere </p>");
assertEquals(" Hello\nthere ", doc.wholeText());
doc = Jsoup.parse("<p>Hello \n there</p>");
assertEquals("Hello \n there", doc.wholeText());
doc = Jsoup.parse("<p>Hello <div>\n there</div></p>");
assertEquals("Hello \n there", doc.wholeText());
}
@Test void wholeTextRuns() {
Document doc = Jsoup.parse("<div><p id=1></p><p id=2> </p><p id=3>. </p>");
Element p1 = doc.expectFirst("#1");
Element p2 = doc.expectFirst("#2");
Element p3 = doc.expectFirst("#3");
assertEquals("", p1.wholeText());
assertEquals(" ", p2.wholeText());
assertEquals(". ", p3.wholeText());
}
@Test void buttonTextHasSpace() {
// https://github.com/jhy/jsoup/issues/2105
Document doc = Jsoup.parse("<html><button>Reply</button><button>All</button></html>");
String text = doc.body().text();
String wholetext = doc.body().wholeText();
assertEquals("Reply All", text);
assertEquals("ReplyAll", wholetext);
}
@Test
public void testGetSiblings() {
Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>");
Element p = doc.getElementById("1");
assertEquals("there", p.text());
assertEquals("Hello", p.previousElementSibling().text());
assertEquals("this", p.nextElementSibling().text());
assertEquals("Hello", p.firstElementSibling().text());
assertEquals("element", p.lastElementSibling().text());
assertNull(p.lastElementSibling().nextElementSibling());
assertNull(p.firstElementSibling().previousElementSibling());
}
@Test public void nextElementSibling() {
Document doc = Jsoup.parse("<p>One</p>Two<p>Three</p>");
Element el = doc.expectFirst("p");
assertNull(el.previousElementSibling());
Element next = el.nextElementSibling();
assertNotNull(next);
assertEquals("Three", next.text());
assertNull(next.nextElementSibling());
}
@Test public void prevElementSibling() {
Document doc = Jsoup.parse("<p>One</p>Two<p>Three</p>");
Element el = doc.expectFirst("p:contains(Three)");
assertNull(el.nextElementSibling());
Element prev = el.previousElementSibling();
assertNotNull(prev);
assertEquals("One", prev.text());
assertNull(prev.previousElementSibling());
}
@Test
public void testGetSiblingsWithDuplicateContent() {
Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>");
Element p = doc.getElementById("1");
assertEquals("there", p.text());
assertEquals("Hello", p.previousElementSibling().text());
assertEquals("this", p.nextElementSibling().text());
assertEquals("this", p.nextElementSibling().nextElementSibling().text());
assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text());
assertEquals("Hello", p.firstElementSibling().text());
assertEquals("element", p.lastElementSibling().text());
}
@Test
public void testFirstElementSiblingOnOrphan() {
Element p = new Element("p");
assertSame(p, p.firstElementSibling());
assertSame(p, p.lastElementSibling());
}
@Test
public void testFirstAndLastSiblings() {
Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three");
Element div = doc.expectFirst("div");
Element one = div.child(0);
Element two = div.child(1);
Element three = div.child(2);
assertSame(one, one.firstElementSibling());
assertSame(one, two.firstElementSibling());
assertSame(three, three.lastElementSibling());
assertSame(three, two.lastElementSibling());
assertNull(one.previousElementSibling());
assertNull(three.nextElementSibling());
}
@Test
public void testGetParents() {
Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>");
Element span = doc.select("span").first();
Elements parents = span.parents();
assertEquals(4, parents.size());
assertEquals("p", parents.get(0).tagName());
assertEquals("div", parents.get(1).tagName());
assertEquals("body", parents.get(2).tagName());
assertEquals("html", parents.get(3).tagName());
Element orphan = new Element("p");
Elements none = orphan.parents();
assertEquals(0, none.size());
}
@Test
public void testElementSiblingIndex() {
Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>");
Elements ps = doc.select("p");
assertEquals(0, ps.get(0).elementSiblingIndex());
assertEquals(1, ps.get(1).elementSiblingIndex());
assertEquals(2, ps.get(2).elementSiblingIndex());
}
@Test
public void testElementSiblingIndexSameContent() {
Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>");
Elements ps = doc.select("p");
assertEquals(0, ps.get(0).elementSiblingIndex());
assertEquals(1, ps.get(1).elementSiblingIndex());
assertEquals(2, ps.get(2).elementSiblingIndex());
}
@Test
public void testGetElementsWithClass() {
Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>");
List<Element> els = doc.getElementsByClass("mellow");
assertEquals(2, els.size());
assertEquals("div", els.get(0).tagName());
assertEquals("span", els.get(1).tagName());
List<Element> els2 = doc.getElementsByClass("yellow");
assertEquals(2, els2.size());
assertEquals("div", els2.get(0).tagName());
assertEquals("b", els2.get(1).tagName());
List<Element> none = doc.getElementsByClass("solo");
assertEquals(0, none.size());
}
@Test
public void testGetElementsWithAttribute() {
Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>");
List<Element> els = doc.getElementsByAttribute("style");
assertEquals(2, els.size());
assertEquals("div", els.get(0).tagName());
assertEquals("b", els.get(1).tagName());
List<Element> none = doc.getElementsByAttribute("class");
assertEquals(0, none.size());
}
@Test
public void testGetElementsWithAttributeDash() {
Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>");
Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]");
assertEquals(1, meta.size());
assertEquals("1", meta.first().id());
}
@Test
public void testGetElementsWithAttributeValue() {
Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>");
List<Element> els = doc.getElementsByAttributeValue("style", "bold");
assertEquals(1, els.size());
assertEquals("div", els.get(0).tagName());
List<Element> none = doc.getElementsByAttributeValue("style", "none");
assertEquals(0, none.size());
}
@Test
public void testClassDomMethods() {
Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>");
List<Element> els = doc.getElementsByAttribute("class");
Element span = els.get(0);
assertEquals("mellow yellow", span.className());
assertTrue(span.hasClass("mellow"));
assertTrue(span.hasClass("yellow"));
Set<String> classes = span.classNames();
assertEquals(2, classes.size());
assertTrue(classes.contains("mellow"));
assertTrue(classes.contains("yellow"));
assertEquals("", doc.className());
classes = doc.classNames();
assertEquals(0, classes.size());
assertFalse(doc.hasClass("mellow"));
}
@Test
public void testHasClassDomMethods() {
Tag tag = Tag.valueOf("a");
Attributes attribs = new Attributes();
Element el = new Element(tag, "", attribs);
attribs.put("class", "toto");
boolean hasClass = el.hasClass("toto");
assertTrue(hasClass);
attribs.put("class", " toto");
hasClass = el.hasClass("toto");
assertTrue(hasClass);
attribs.put("class", "toto ");
hasClass = el.hasClass("toto");
assertTrue(hasClass);
attribs.put("class", "\ttoto ");
hasClass = el.hasClass("toto");
assertTrue(hasClass);
attribs.put("class", " toto ");
hasClass = el.hasClass("toto");
assertTrue(hasClass);
attribs.put("class", "ab");
hasClass = el.hasClass("toto");
assertFalse(hasClass);
attribs.put("class", " ");
hasClass = el.hasClass("toto");
assertFalse(hasClass);
attribs.put("class", "tototo");
hasClass = el.hasClass("toto");
assertFalse(hasClass);
attribs.put("class", "raulpismuth ");
hasClass = el.hasClass("raulpismuth");
assertTrue(hasClass);
attribs.put("class", " abcd raulpismuth efgh ");
hasClass = el.hasClass("raulpismuth");
assertTrue(hasClass);
attribs.put("class", " abcd efgh raulpismuth");
hasClass = el.hasClass("raulpismuth");
assertTrue(hasClass);
attribs.put("class", " abcd efgh raulpismuth ");
hasClass = el.hasClass("raulpismuth");
assertTrue(hasClass);
}
@Test
public void testClassUpdates() {
Document doc = Jsoup.parse("<div class='mellow yellow'></div>");
Element div = doc.select("div").first();
div.addClass("green");
assertEquals("mellow yellow green", div.className());
div.removeClass("red"); // noop
div.removeClass("yellow");
assertEquals("mellow green", div.className());
div.toggleClass("green").toggleClass("red");
assertEquals("mellow red", div.className());
}
@Test
public void testOuterHtml() {
Document doc = Jsoup.parse("<div title='Tags &c.'><img src=foo.png><p><!-- comment -->Hello<p>there");
assertEquals("<html><head></head><body><div title=\"Tags &c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>",
TextUtil.stripNewlines(doc.outerHtml()));
}
@Test
public void testInnerHtml() {
Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>");
assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html());
}
@Test void formatNoTrailingSpace() {
// https://github.com/jhy/jsoup/issues/2215
String html = "<html>\n <head></head>\n <body>\n a\n <div>\n </div>\n </body>\n</html>";
Document doc = Jsoup.parse(html);
assertEquals("<html>\n <head></head>\n <body>\n a\n <div></div>\n </body>\n</html>", doc.html());
}
@Test
public void testFormatHtml() {
Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>");
assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html());
}
@Test
public void testFormatOutline() {
Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>");
doc.outputSettings().outline(true);
assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello\n <span>\n jsoup\n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html());
}
@Test
public void testSetIndent() {
Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>");
doc.outputSettings().indentAmount(0);
assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html());
}
@Test void testIndentLevel() {
// deep to test default and extended max
StringBuilder divs = new StringBuilder();
for (int i = 0; i < 40; i++) {
divs.append("<div>");
}
divs.append("Foo");
Document doc = Jsoup.parse(divs.toString());
Document.OutputSettings settings = doc.outputSettings();
int defaultMax = 30;
assertEquals(defaultMax, settings.maxPaddingWidth());
String html = doc.html();
assertTrue(html.contains("\n" + StringUtil.padding(defaultMax, -1) + "<div>Foo</div>\n"));
settings.maxPaddingWidth(32);
assertEquals(32, settings.maxPaddingWidth());
html = doc.html();
assertTrue(html.contains("\n" + StringUtil.padding(32, -1) + "<div>Foo</div>\n"));
settings.maxPaddingWidth(-1);
assertEquals(-1, settings.maxPaddingWidth());
html = doc.html();
assertTrue(html.contains("\n" + StringUtil.padding(41, -1) + "<div>Foo</div>\n"));
}
@Test
public void testNotPretty() {
Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>");
doc.outputSettings().prettyPrint(false);
assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html());
Element div = doc.select("div").first();
assertEquals(" \n<p>Hello\n there\n</p>", div.html());
}
@Test
public void testNotPrettyWithEnDashBody() {
String html = "<div><span>1:15</span>–<span>2:15</span> p.m.</div>";
Document document = Jsoup.parse(html);
document.outputSettings().prettyPrint(false);
assertEquals("<div><span>1:15</span>–<span>2:15</span> p.m.</div>", document.body().html());
}
@Test
public void testPrettyWithEnDashBody() {
String html = "<div><span>1:15</span>–<span>2:15</span> p.m.</div>";
Document document = Jsoup.parse(html);
assertEquals("<div>\n <span>1:15</span>–<span>2:15</span> p.m.\n</div>", document.body().html());
}
@Test
public void testPrettyAndOutlineWithEnDashBody() {
String html = "<div><span>1:15</span>–<span>2:15</span> p.m.</div>";
Document document = Jsoup.parse(html);
document.outputSettings().outline(true);
assertEquals("<div>\n <span>1:15</span>\n –\n <span>2:15</span>\n p.m.\n</div>", document.body().html());
}
@Test
public void testBasicFormats() {
String html = "<span>0</span>.<div><span>1</span>-<span>2</span><p> <span>3</span>-<span>4</span><div> 5 </div>";
Document doc = Jsoup.parse(html);
assertEquals(
"<span>0</span>.\n" +
"<div>\n" +
" <span>1</span>-<span>2</span>\n" +
" <p><span>3</span>-<span>4</span></p>\n" +
" <div>5</div>\n" +
"</div>", doc.body().html());
}
@Test
public void testEmptyElementFormatHtml() {
// don't put newlines into empty blocks
Document doc = Jsoup.parse("<section><div></div></section>");
assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml());
}
@Test
public void testNoIndentOnScriptAndStyle() {
// don't newline+indent closing </script> and </style> tags
Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>");
assertEquals("<script>one\ntwo</script>\n<style>three\nfour</style>", doc.head().html());
}
@Test
public void testContainerOutput() {
Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>");
assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml());
assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml());
assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>\n<div>Another</div>", doc.select("body").first().html());
}
@Test
public void testSetText() {
String h = "<div id=1>Hello <p>there <b>now</b></p></div>";
Document doc = Jsoup.parse(h);
assertEquals("Hello there now", doc.text()); // need to sort out node whitespace
assertEquals("there now", doc.select("p").get(0).text());
Element div = doc.getElementById("1").text("Gone");
assertEquals("Gone", div.text());
assertEquals(0, doc.select("p").size());
}
@Test
public void testAddNewElement() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.appendElement("p").text("there");
div.appendElement("P").attr("CLASS", "second").text("now");
// manually specifying tag and attributes should maintain case based on parser settings
assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>",
TextUtil.stripNewlines(doc.html()));
// check sibling index (with short circuit on reindexChildren):
Elements ps = doc.select("p");
for (int i = 0; i < ps.size(); i++) {
assertEquals(i, ps.get(i).siblingIndex);
}
}
@Test
public void testAddBooleanAttribute() {
Element div = new Element(Tag.valueOf("div"), "");
div.attr("true", true);
div.attr("false", "value");
div.attr("false", false);
assertTrue(div.hasAttr("true"));
assertEquals("", div.attr("true"));
List<Attribute> attributes = div.attributes().asList();
assertEquals(1, attributes.size(), "There should be one attribute");
assertFalse(div.hasAttr("false"));
assertEquals("<div true></div>", div.outerHtml());
}
@Test
public void testAppendRowToTable() {
Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>");
Element table = doc.select("tbody").first();
table.append("<tr><td>2</td></tr>");
assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testPrependRowToTable() {
Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>");
Element table = doc.select("tbody").first();
table.prepend("<tr><td>2</td></tr>");
assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html()));
// check sibling index (reindexChildren):
Elements ps = doc.select("tr");
for (int i = 0; i < ps.size(); i++) {
assertEquals(i, ps.get(i).siblingIndex);
}
}
@Test
public void testPrependElement() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.prependElement("p").text("Before");
assertEquals("Before", div.child(0).text());
assertEquals("Hello", div.child(1).text());
}
@Test
public void testAddNewText() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.appendText(" there & now >");
assertEquals ("Hello there & now >", div.text());
assertEquals("<p>Hello</p>there & now >", TextUtil.stripNewlines(div.html()));
}
@Test
public void testPrependText() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.prependText("there & now > ");
assertEquals("there & now > Hello", div.text());
assertEquals("there & now >\n<p>Hello</p>", div.html());
}
@Test
public void testThrowsOnAddNullText() {
assertThrows(IllegalArgumentException.class, () -> {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.appendText(null);
});
}
@Test
public void testThrowsOnPrependNullText() {
assertThrows(IllegalArgumentException.class, () -> {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.prependText(null);
});
}
@Test
public void testAddNewHtml() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.append("<p>there</p><p>now</p>");
assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html()));
// check sibling index (no reindexChildren):
Elements ps = doc.select("p");
for (int i = 0; i < ps.size(); i++) {
assertEquals(i, ps.get(i).siblingIndex);
}
}
@Test
public void testPrependNewHtml() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.prepend("<p>there</p><p>now</p>");
assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html()));
// check sibling index (reindexChildren):
Elements ps = doc.select("p");
for (int i = 0; i < ps.size(); i++) {
assertEquals(i, ps.get(i).siblingIndex);
}
}
@Test void prependNodes() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element p = doc.expectFirst("p");
p.prepend("Text <!-- comment --> ");
assertEquals("Text <!-- comment --> Hello", TextUtil.stripNewlines(p.html()));
}
@Test void appendNodes() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element p = doc.expectFirst("p");
p.append(" Text <!-- comment -->");
assertEquals("Hello Text <!-- comment -->", TextUtil.stripNewlines(p.html()));
}
@Test
public void testSetHtml() {
Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>");
Element div = doc.getElementById("1");
div.html("<p>there</p><p>now</p>");
assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html()));
}
@Test
public void testSetHtmlTitle() {
Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>");
Element title = doc.getElementById("1");
title.html("good");
assertEquals("good", title.html());
title.html("<i>bad</i>");
assertEquals("<i>bad</i>", title.html());
Element head = doc.getElementById("2");
head.html("<title><i>bad</i></title>");
assertEquals("<title><i>bad</i></title>", head.html());
}
@Test
public void testWrap() {
Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>");
Element p = doc.select("p").first();
p.wrap("<div class='head'></div>");
assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html()));
Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>");
assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>",
TextUtil.stripNewlines(doc.body().html()));
assertEquals(ret, p);
}
@Test
public void testWrapNoop() {
Document doc = Jsoup.parse("<div><p>Hello</p></div>");
Node p = doc.select("p").first();
Node wrapped = p.wrap("Some junk");
assertSame(p, wrapped);
assertEquals("<div><p>Hello</p></div>", TextUtil.stripNewlines(doc.body().html()));
// should be a NOOP
}
@Test
public void testWrapOnOrphan() {
Element orphan = new Element("span").text("Hello!");
assertFalse(orphan.hasParent());
Element wrapped = orphan.wrap("<div></div> There!");
assertSame(orphan, wrapped);
assertTrue(orphan.hasParent()); // should now be in the DIV
assertNotNull(orphan.parent());
assertEquals("div", orphan.parent().tagName());
assertEquals("<div>\n <span>Hello!</span>\n</div>", orphan.parent().outerHtml());
}
@Test
public void testWrapArtificialStructure() {
// div normally couldn't get into a p, but explicitly want to wrap
Document doc = Jsoup.parse("<p>Hello <i>there</i> now.");
Element i = doc.expectFirst("i");
i.wrap("<div id=id1></div> quite");
assertEquals("div", i.parent().tagName());
assertEquals("<p>Hello\n <div id=\"id1\">\n <i>there</i>\n </div>\n quite now.</p>",(doc.body().html()));
// gives us a TextNode seq of "quite" and " now"; make sure not to collapse to "quitenow" when pretty print.
}
@Test
public void before() {
Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>");
Element p1 = doc.select("p").first();
p1.before("<div>one</div><div>two</div>");
assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html()));
doc.select("p").last().before("<p>Three</p><!-- four -->");
assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void after() {
Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>");
Element p1 = doc.select("p").first();
p1.after("<div>one</div><div>two</div>");
assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html()));
doc.select("p").last().after("<p>Three</p><!-- four -->");
assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testWrapWithRemainder() {
Document doc = Jsoup.parse("<div><p>Hello</p></div>");
Element p = doc.select("p").first();
p.wrap("<div class='head'></div><p>There!</p>");
assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There!</p></div>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testWrapWithSimpleRemainder() {
Document doc = Jsoup.parse("<p>Hello");
Element p = doc.selectFirst("p");
Element body = p.parent();
assertNotNull(body);
assertEquals("body", body.tagName());
p.wrap("<div></div> There");
Element div = p.parent();
assertNotNull(div);
assertEquals("div", div.tagName());
assertSame(div, p.parent());
assertSame(body, div.parent());
assertEquals("<div><p>Hello</p></div>There", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testHasText() {
Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>");
Element div = doc.select("div").first();
Elements ps = doc.select("p");
assertTrue(div.hasText());
assertTrue(ps.first().hasText());
assertFalse(ps.last().hasText());
}
@Test
public void dataset() {
Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>");
Element div = doc.select("div").first();
Map<String, String> dataset = div.dataset();
Attributes attributes = div.attributes();
// size, get, set, add, remove
assertEquals(2, dataset.size());
assertEquals("jsoup", dataset.get("name"));
assertEquals("jar", dataset.get("package"));
dataset.put("name", "jsoup updated");
dataset.put("language", "java");
dataset.remove("package");
assertEquals(2, dataset.size());
assertEquals(4, attributes.size());
assertEquals("jsoup updated", attributes.get("data-name"));
assertEquals("jsoup updated", dataset.get("name"));
assertEquals("java", attributes.get("data-language"));
assertEquals("java", dataset.get("language"));
attributes.put("data-food", "bacon");
assertEquals(3, dataset.size());
assertEquals("bacon", dataset.get("food"));
attributes.put("data-", "empty");
assertNull(dataset.get("")); // data- is not a data attribute
Element p = doc.select("p").first();
assertEquals(0, p.dataset().size());
}
@Test
public void parentlessToString() {
Document doc = Jsoup.parse("<img src='foo'>");
Element img = doc.select("img").first();
assertEquals("<img src=\"foo\">", img.toString());
img.remove(); // lost its parent
assertEquals("<img src=\"foo\">", img.toString());
}
@Test
public void orphanDivToString() {
Element orphan = new Element("div").id("foo").text("Hello");
assertEquals("<div id=\"foo\">Hello</div>", orphan.toString());
}
@Test
public void testClone() {
Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>");
Element p = doc.select("p").get(1);
Element clone = p.clone();
assertNotNull(clone.parentNode); // should be a cloned document just containing this clone
assertEquals(1, clone.parentNode.childNodeSize());
assertSame(clone.ownerDocument(), clone.parentNode);
assertEquals(0, clone.siblingIndex);
assertEquals(1, p.siblingIndex);
assertNotNull(p.parent());
clone.append("<span>Three");
assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml()));
assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified
doc.body().appendChild(clone); // adopt
assertNotNull(clone.parent());
assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testClonesClassnames() {
Document doc = Jsoup.parse("<div class='one two'></div>");
Element div = doc.select("div").first();
Set<String> classes = div.classNames();
assertEquals(2, classes.size());
assertTrue(classes.contains("one"));
assertTrue(classes.contains("two"));
Element copy = div.clone();
Set<String> copyClasses = copy.classNames();
assertEquals(2, copyClasses.size());
assertTrue(copyClasses.contains("one"));
assertTrue(copyClasses.contains("two"));
copyClasses.add("three");
copyClasses.remove("one");
assertTrue(classes.contains("one"));
assertFalse(classes.contains("three"));
assertFalse(copyClasses.contains("one"));
assertTrue(copyClasses.contains("three"));
assertEquals("", div.html());
assertEquals("", copy.html());
}
@Test
public void testShallowClone() {
String base = "http://example.com/";
Document doc = Jsoup.parse("<div id=1 class=one><p id=2 class=two>One", base);
Element d = doc.selectFirst("div");
Element p = doc.selectFirst("p");
TextNode t = p.textNodes().get(0);
Element d2 = d.shallowClone();
Element p2 = p.shallowClone();
TextNode t2 = (TextNode) t.shallowClone();
assertEquals(1, d.childNodeSize());
assertEquals(0, d2.childNodeSize());
assertEquals(1, p.childNodeSize());
assertEquals(0, p2.childNodeSize());
assertEquals("", p2.text());
assertEquals("One", t2.text());
assertEquals("two", p2.className());
p2.removeClass("two");
assertEquals("two", p.className());
d2.append("<p id=3>Three");
assertEquals(1, d2.childNodeSize());
assertEquals("Three", d2.text());
assertEquals("One", d.text());
assertEquals(base, d2.baseUri());
}
@Test void cloneRetainsParser() {
Document htmlDoc = Jsoup.parse("<div><script></script></div>", Parser.htmlParser());
Document xmlDoc = Jsoup.parse("<div><script></script></div>", Parser.xmlParser());
Element hEl = htmlDoc.expectFirst("script");
Element hEl2 = hEl.clone();
assertNotSame(hEl, hEl2);
assertNotSame(hEl.ownerDocument(), hEl2.ownerDocument());
assertSame(hEl.ownerDocument().parser(), hEl2.ownerDocument().parser());
Document doc2 = htmlDoc.clone();
assertNotSame(htmlDoc, doc2);
assertSame(htmlDoc.parser(), doc2.parser());
hEl2.append("<foo></foo>"); // we are inside a script, should be parsed as data
assertEquals("<foo></foo>", hEl2.data());
Element xEl = xmlDoc.expectFirst("script");
Element xEl2 = xEl.clone();
xEl2.append("<foo></foo>"); // in XML, script doesn't mean anything, and so will be parsed as xml
assertEquals("<script><foo></foo></script>", xEl2.outerHtml());
}
@Test
public void testTagNameSet() {
Document doc = Jsoup.parse("<div><i>Hello</i>");
doc.select("i").first().tagName("em");
assertEquals(0, doc.select("i").size());
assertEquals(1, doc.select("em").size());
assertEquals("<em>Hello</em>", doc.select("div").first().html());
}
@Test void testSetTag() {
Document doc = Jsoup.parse("<div><em>Hello</em></div>");
Element el = doc.expectFirst("em");
el.tag(new Tag("I", NamespaceHtml));
assertEquals("<I>Hello</I>", el.outerHtml()); // case-sensitive path
}
@Test
public void testHtmlContainsOuter() {
Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>");
doc.outputSettings().indentAmount(0);
assertTrue(doc.html().contains(doc.select("title").outerHtml()));
assertTrue(doc.html().contains(doc.select("div").outerHtml()));
}
@Test
public void testGetTextNodes() {
Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>");
List<TextNode> textNodes = doc.select("p").first().textNodes();
assertEquals(3, textNodes.size());
assertEquals("One ", textNodes.get(0).text());
assertEquals(" Three ", textNodes.get(1).text());
assertEquals(" Four", textNodes.get(2).text());
assertEquals(0, doc.select("br").first().textNodes().size());
}
@Test
public void testManipulateTextNodes() {
Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>");
Element p = doc.select("p").first();
List<TextNode> textNodes = p.textNodes();
textNodes.get(1).text(" three-more ");
textNodes.get(2).splitText(3).text("-ur");
assertEquals("One Two three-more Fo-ur", p.text());
assertEquals("One three-more Fo-ur", p.ownText());
assertEquals(4, p.textNodes().size()); // grew because of split
}
@Test
public void testGetDataNodes() {
Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>");
Element script = doc.select("script").first();
Element style = doc.select("style").first();
Element p = doc.select("p").first();
List<DataNode> scriptData = script.dataNodes();
assertEquals(1, scriptData.size());
assertEquals("One Two", scriptData.get(0).getWholeData());
List<DataNode> styleData = style.dataNodes();
assertEquals(1, styleData.size());
assertEquals("Three Four", styleData.get(0).getWholeData());
List<DataNode> pData = p.dataNodes();
assertEquals(0, pData.size());
}
@Test
public void elementIsNotASiblingOfItself() {
Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>");
Element p2 = doc.select("p").get(1);
assertEquals("Two", p2.text());
Elements els = p2.siblingElements();
assertEquals(2, els.size());
assertEquals("<p>One</p>", els.get(0).outerHtml());
assertEquals("<p>Three</p>", els.get(1).outerHtml());
}
@Test
public void testChildThrowsIndexOutOfBoundsOnMissing() {
Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>");
Element div = doc.select("div").first();
assertEquals(2, div.children().size());
assertEquals("One", div.child(0).text());
try {
div.child(3);
fail("Should throw index out of bounds");
} catch (IndexOutOfBoundsException e) {
}
}
@Test
public void moveByAppend() {
// test for https://github.com/jhy/jsoup/issues/239
// can empty an element and append its children to another element
Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>");
Element div1 = doc.select("div").get(0);
Element div2 = doc.select("div").get(1);
assertEquals(4, div1.childNodeSize());
List<Node> children = div1.childNodes();
assertEquals(4, children.size());
div2.insertChildren(0, children);
assertEquals(4, children.size()); // children is NOT backed by div1.childNodes but a wrapper, so should still be 4 (but re-parented)
assertEquals(0, div1.childNodeSize());
assertEquals(4, div2.childNodeSize());
assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text\n <p>One</p>\n Text\n <p>Two</p>\n</div>", doc.body().html());
}
@Test
public void insertChildrenArgumentValidation() {
Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>");
Element div1 = doc.select("div").get(0);
Element div2 = doc.select("div").get(1);
List<Node> children = div1.childNodes();
try {
div2.insertChildren(6, children);
fail();
} catch (IllegalArgumentException e) {
}
try {
div2.insertChildren(-5, children);
fail();
} catch (IllegalArgumentException e) {
}
try {
div2.insertChildren(0, (Collection<? extends Node>) null);
fail();
} catch (IllegalArgumentException e) {
}
}
@Test
public void insertChildrenAtPosition() {
Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>");
Element div1 = doc.select("div").get(0);
Elements p1s = div1.select("p");
Element div2 = doc.select("div").get(1);
assertEquals(2, div2.childNodeSize());
div2.insertChildren(-1, p1s);
assertEquals(2, div1.childNodeSize()); // moved two out
assertEquals(4, div2.childNodeSize());
assertEquals(3, p1s.get(1).siblingIndex()); // should be last
List<Node> els = new ArrayList<>();
Element el1 = new Element(Tag.valueOf("span"), "").text("Span1");
Element el2 = new Element(Tag.valueOf("span"), "").text("Span2");
TextNode tn1 = new TextNode("Text4");
els.add(el1);
els.add(el2);
els.add(tn1);
assertNull(el1.parent());
div2.insertChildren(-2, els);
assertEquals(div2, el1.parent());
assertEquals(7, div2.childNodeSize());
assertEquals(3, el1.siblingIndex());
assertEquals(4, el2.siblingIndex());
assertEquals(5, tn1.siblingIndex());
}
@Test
public void insertChildrenAsCopy() {
Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>");
Element div1 = doc.select("div").get(0);
Element div2 = doc.select("div").get(1);
Elements ps = doc.select("p").clone();
ps.first().text("One cloned");
div2.insertChildren(-1, ps);
assertEquals(4, div1.childNodeSize()); // not moved -- cloned
assertEquals(2, div2.childNodeSize());
assertEquals(
"<div id=\"1\">\n Text\n <p>One</p>\n Text\n <p>Two</p>\n</div>\n<div id=\"2\">\n <p>One cloned</p>\n <p>Two</p>\n</div>",
doc.body().html()
);
}
@Test
public void testCssPath() {
Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>");
Element divA = doc.select("div").get(0);
Element divB = doc.select("div").get(1);
Element divC = doc.select("div").get(2);
assertEquals(divA.cssSelector(), "#id1");
assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)");
assertEquals(divC.cssSelector(), "html > body > div.c1.c2");
assertSame(divA, doc.select(divA.cssSelector()).first());
assertSame(divB, doc.select(divB.cssSelector()).first());
assertSame(divC, doc.select(divC.cssSelector()).first());
}
@Test
public void testCssPathDuplicateIds() {
// https://github.com/jhy/jsoup/issues/1147 - multiple elements with same ID, use the non-ID form
Document doc = Jsoup.parse("<article><div id=dupe>A</div><div id=dupe>B</div><div id=dupe class=c1>");
Element divA = doc.select("div").get(0);
Element divB = doc.select("div").get(1);
Element divC = doc.select("div").get(2);
assertEquals(divA.cssSelector(), "html > body > article > div:nth-child(1)");
assertEquals(divB.cssSelector(), "html > body > article > div:nth-child(2)");
assertEquals(divC.cssSelector(), "html > body > article > div.c1");
assertSame(divA, doc.select(divA.cssSelector()).first());
assertSame(divB, doc.select(divB.cssSelector()).first());
assertSame(divC, doc.select(divC.cssSelector()).first());
}
@Test public void cssSelectorEscaped() {
// https://github.com/jhy/jsoup/issues/1742
Document doc = Jsoup.parse("<p\\p>One</p\\p> <p id='one.two'>Two</p> <p class='one.two:three/four'>Three</p>");
Element one = doc.expectFirst("p\\\\p");
Elements ps = doc.select("p");
Element two = ps.get(0);
Element three = ps.get(1);
String oneSelect = one.cssSelector();
assertEquals("html > body > p\\\\p", oneSelect);
assertEquals(one, doc.expectFirst(oneSelect));
String twoSelect = two.cssSelector();
assertEquals("#one\\.two", twoSelect);
assertEquals(two, doc.expectFirst(twoSelect));
String threeSelect = three.cssSelector();
assertEquals("html > body > p.one\\.two\\:three\\/four", threeSelect);
assertEquals(three, doc.expectFirst(threeSelect));
}
@Test public void cssEscapedAmp() {
Document doc = Jsoup.parse("<p class='\\&'>One</p>");
Element one = doc.expectFirst(".\\\\\\&"); // tested matches js querySelector
assertEquals("One", one.text());
String q = one.cssSelector();
assertEquals("html > body > p.\\\\\\&", q);
assertEquals(one, doc.expectFirst(q));
}
@Test public void cssSelectorEscapedClass() {
// example in https://github.com/jhy/jsoup/issues/838
String html = "<div class='B\\&W\\?'><div class=test>Text</div></div>";
Document parse = Jsoup.parse(html);
Element el = parse.expectFirst(".test");
assertEquals("Text", el.text());
String q = el.cssSelector();
assertEquals("html > body > div.B\\\\\\&W\\\\\\? > div.test", q);
Element found = parse.expectFirst(q);
assertEquals(found, el);
}
@Test
public void testClassNames() {
Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>");
Element div = doc.select("div").get(0);
assertEquals("c1 c2", div.className());
final Set<String> set1 = div.classNames();
final Object[] arr1 = set1.toArray();
assertEquals(2, arr1.length);
assertEquals("c1", arr1[0]);
assertEquals("c2", arr1[1]);
// Changes to the set should not be reflected in the Elements getters
set1.add("c3");
assertEquals(2, div.classNames().size());
assertEquals("c1 c2", div.className());
// Update the
|
ElementTest
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
|
{
"start": 28154,
"end": 30328
}
|
class ____ extends LookupElement {
private final String beanName;
public EjbRefElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
super(member, pd);
jakarta.ejb.EJB resource = ae.getAnnotation(jakarta.ejb.EJB.class);
String resourceBeanName = resource.beanName();
String resourceName = resource.name();
this.isDefaultName = !StringUtils.hasLength(resourceName);
if (this.isDefaultName) {
resourceName = this.member.getName();
if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) {
resourceName = StringUtils.uncapitalizeAsProperty(resourceName.substring(3));
}
}
Class<?> resourceType = resource.beanInterface();
if (Object.class != resourceType) {
checkResourceType(resourceType);
}
else {
// No resource type specified... check field/method.
resourceType = getResourceType();
}
this.beanName = resourceBeanName;
this.name = resourceName;
this.lookupType = resourceType;
this.mappedName = resource.mappedName();
}
@Override
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
if (StringUtils.hasLength(this.beanName)) {
if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
// Local match found for explicitly specified local bean name.
Object bean = beanFactory.getBean(this.beanName, this.lookupType);
if (requestingBeanName != null && beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) {
configurableBeanFactory.registerDependentBean(this.beanName, requestingBeanName);
}
return bean;
}
else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) {
throw new NoSuchBeanDefinitionException(this.beanName,
"Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead.");
}
}
// JNDI name lookup - may still go to a local BeanFactory.
return getResource(this, requestingBeanName);
}
}
/**
* {@link BeanRegistrationAotContribution} to inject resources on fields and methods.
*/
private static
|
EjbRefElement
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/FluxWindow.java
|
{
"start": 7122,
"end": 11282
}
|
class ____<T>
implements Disposable, InnerOperator<T, Flux<T>> {
final CoreSubscriber<? super Flux<T>> actual;
final Context ctx;
final Supplier<? extends Queue<T>> processorQueueSupplier;
final int size;
final int skip;
volatile int cancelled;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<WindowSkipSubscriber> CANCELLED =
AtomicIntegerFieldUpdater.newUpdater(WindowSkipSubscriber.class, "cancelled");
volatile int windowCount;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<WindowSkipSubscriber> WINDOW_COUNT =
AtomicIntegerFieldUpdater.newUpdater(WindowSkipSubscriber.class, "windowCount");
volatile int firstRequest;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<WindowSkipSubscriber> FIRST_REQUEST =
AtomicIntegerFieldUpdater.newUpdater(WindowSkipSubscriber.class,
"firstRequest");
int index;
@SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe
Subscription s;
Sinks.@Nullable Many<T> window;
boolean done;
WindowSkipSubscriber(CoreSubscriber<? super Flux<T>> actual,
int size,
int skip,
Supplier<? extends Queue<T>> processorQueueSupplier) {
this.actual = actual;
this.ctx = actual.currentContext();
this.size = size;
this.skip = skip;
this.processorQueueSupplier = processorQueueSupplier;
WINDOW_COUNT.lazySet(this, 1);
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
actual.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (done) {
Operators.onNextDropped(t, ctx);
return;
}
int i = index;
Sinks.Many<T> w = window;
if (i == 0) {
WINDOW_COUNT.getAndIncrement(this);
w = Sinks.unsafe().many().unicast().onBackpressureBuffer(processorQueueSupplier.get(), this);
window = w;
actual.onNext(w.asFlux());
}
i++;
if (w != null) {
w.emitNext(t, Sinks.EmitFailureHandler.FAIL_FAST);
}
else {
Operators.onDiscard(t, ctx);
}
if (i == size) {
window = null;
if (w != null) {
w.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
}
}
if (i == skip) {
index = 0;
}
else {
index = i;
}
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t, ctx);
return;
}
done = true;
Sinks.Many<T> w = window;
if (w != null) {
window = null;
w.emitError(wrapSource(t), Sinks.EmitFailureHandler.FAIL_FAST);
}
actual.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
Sinks.Many<T> w = window;
if (w != null) {
window = null;
w.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
}
actual.onComplete();
}
@Override
public void request(long n) {
if (Operators.validate(n)) {
if (firstRequest == 0 && FIRST_REQUEST.compareAndSet(this, 0, 1)) {
long u = Operators.multiplyCap(size, n);
long v = Operators.multiplyCap(skip - size, n - 1);
long w = Operators.addCap(u, v);
s.request(w);
}
else {
long u = Operators.multiplyCap(skip, n);
s.request(u);
}
}
}
@Override
public void cancel() {
if (CANCELLED.compareAndSet(this, 0, 1)) {
dispose();
}
}
@Override
public boolean isDisposed() {
return cancelled == 1 || done;
}
@Override
public void dispose() {
if (WINDOW_COUNT.decrementAndGet(this) == 0) {
s.cancel();
}
}
@Override
public CoreSubscriber<? super Flux<T>> actual() {
return actual;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return s;
if (key == Attr.CANCELLED) return cancelled == 1;
if (key == Attr.CAPACITY) return size;
if (key == Attr.TERMINATED) return done;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return InnerOperator.super.scanUnsafe(key);
}
@Override
public Stream<? extends Scannable> inners() {
return Stream.of(Scannable.from(window));
}
}
static final
|
WindowSkipSubscriber
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/builder/BuilderSimpleTest.java
|
{
"start": 3747,
"end": 4006
}
|
class ____ implements ValueInterface2
{
final int _x;
protected ValueInterface2Impl(int x) {
_x = x+1;
}
@Override
public int getX() {
return _x;
}
}
static
|
ValueInterface2Impl
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/executor/loader/ResultLoaderMap.java
|
{
"start": 1692,
"end": 3683
}
|
class ____ {
private final Map<String, LoadPair> loaderMap = new HashMap<>();
public void addLoader(String property, MetaObject metaResultObject, ResultLoader resultLoader) {
String upperFirst = getUppercaseFirstProperty(property);
if (!upperFirst.equalsIgnoreCase(property) && loaderMap.containsKey(upperFirst)) {
throw new ExecutorException("Nested lazy loaded result property '" + property + "' for query id '"
+ resultLoader.mappedStatement.getId()
+ " already exists in the result map. The leftmost property of all lazy loaded properties must be unique within a result map.");
}
loaderMap.put(upperFirst, new LoadPair(property, metaResultObject, resultLoader));
}
public final Map<String, LoadPair> getProperties() {
return new HashMap<>(this.loaderMap);
}
public Set<String> getPropertyNames() {
return loaderMap.keySet();
}
public int size() {
return loaderMap.size();
}
public boolean isEmpty() {
return loaderMap.isEmpty();
}
public boolean hasLoader(String property) {
return loaderMap.containsKey(property.toUpperCase(Locale.ENGLISH));
}
public boolean load(String property) throws SQLException {
LoadPair pair = loaderMap.remove(property.toUpperCase(Locale.ENGLISH));
if (pair != null) {
pair.load();
return true;
}
return false;
}
public void remove(String property) {
loaderMap.remove(property.toUpperCase(Locale.ENGLISH));
}
public void loadAll() throws SQLException {
final Set<String> methodNameSet = loaderMap.keySet();
String[] methodNames = methodNameSet.toArray(new String[methodNameSet.size()]);
for (String methodName : methodNames) {
load(methodName);
}
}
private static String getUppercaseFirstProperty(String property) {
String[] parts = property.split("\\.");
return parts[0].toUpperCase(Locale.ENGLISH);
}
/**
* Property which was not loaded yet.
*/
public static
|
ResultLoaderMap
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/serde/RexNodeJsonDeserializer.java
|
{
"start": 7844,
"end": 33453
}
|
class ____ extends StdDeserializer<RexNode> {
private static final long serialVersionUID = 1L;
RexNodeJsonDeserializer() {
super(RexNode.class);
}
@Override
public RexNode deserialize(JsonParser jsonParser, DeserializationContext ctx)
throws IOException {
final JsonNode jsonNode = jsonParser.readValueAsTree();
final SerdeContext serdeContext = SerdeContext.get(ctx);
return deserialize(jsonNode, serdeContext);
}
private static RexNode deserialize(JsonNode jsonNode, SerdeContext serdeContext)
throws IOException {
final String kind = jsonNode.required(FIELD_NAME_KIND).asText();
switch (kind) {
case KIND_INPUT_REF:
return deserializeInputRef(jsonNode, serdeContext);
case KIND_LITERAL:
return deserializeLiteral(jsonNode, serdeContext);
case KIND_FIELD_ACCESS:
return deserializeFieldAccess(jsonNode, serdeContext);
case KIND_CORREL_VARIABLE:
return deserializeCorrelVariable(jsonNode, serdeContext);
case KIND_PATTERN_INPUT_REF:
return deserializePatternFieldRef(jsonNode, serdeContext);
case KIND_TABLE_ARG_CALL:
return deserializeTableArgCall(jsonNode, serdeContext);
case KIND_CALL:
return deserializeCall(jsonNode, serdeContext);
default:
throw new TableException("Cannot convert to RexNode: " + jsonNode.toPrettyString());
}
}
private static RexNode deserializeInputRef(JsonNode jsonNode, SerdeContext serdeContext) {
final int inputIndex = jsonNode.required(FIELD_NAME_INPUT_INDEX).intValue();
final JsonNode logicalTypeNode = jsonNode.required(FIELD_NAME_TYPE);
final RelDataType fieldType =
RelDataTypeJsonDeserializer.deserialize(logicalTypeNode, serdeContext);
return serdeContext.getRexBuilder().makeInputRef(fieldType, inputIndex);
}
private static RexNode deserializeLiteral(JsonNode jsonNode, SerdeContext serdeContext) {
final JsonNode logicalTypeNode = jsonNode.required(FIELD_NAME_TYPE);
final RelDataType relDataType =
RelDataTypeJsonDeserializer.deserialize(logicalTypeNode, serdeContext);
if (jsonNode.has(FIELD_NAME_SARG)) {
return deserializeSarg(jsonNode.required(FIELD_NAME_SARG), relDataType, serdeContext);
} else if (jsonNode.has(FIELD_NAME_VALUE)) {
final Object value =
deserializeLiteralValue(jsonNode, relDataType.getSqlTypeName(), serdeContext);
if (value == null) {
return serdeContext.getRexBuilder().makeNullLiteral(relDataType);
}
return serdeContext.getRexBuilder().makeLiteral(value, relDataType, true);
} else {
throw new TableException("Unknown literal: " + jsonNode.toPrettyString());
}
}
@SuppressWarnings({"UnstableApiUsage", "rawtypes", "unchecked"})
private static RexNode deserializeSarg(
JsonNode sargNode, RelDataType relDataType, SerdeContext serdeContext) {
final RexBuilder rexBuilder = serdeContext.getRexBuilder();
final ArrayNode rangesNode = (ArrayNode) sargNode.required(FIELD_NAME_RANGES);
final Builder builder = builder();
for (JsonNode rangeNode : rangesNode) {
Range range = all();
if (rangeNode.has(FIELD_NAME_BOUND_LOWER)) {
final JsonNode lowerNode = rangeNode.required(FIELD_NAME_BOUND_LOWER);
final Comparable<?> boundValue =
(Comparable<?>)
deserializeLiteralValue(
lowerNode, relDataType.getSqlTypeName(), serdeContext);
assert boundValue != null;
final BoundType boundType =
serializableToCalcite(
BoundType.class,
lowerNode.required(FIELD_NAME_BOUND_TYPE).asText());
final Range<?> r =
boundType == BoundType.OPEN ? greaterThan(boundValue) : atLeast(boundValue);
range = range.intersection(r);
}
if (rangeNode.has(FIELD_NAME_BOUND_UPPER)) {
final JsonNode upperNode = rangeNode.required(FIELD_NAME_BOUND_UPPER);
final Comparable<?> boundValue =
(Comparable<?>)
deserializeLiteralValue(
upperNode, relDataType.getSqlTypeName(), serdeContext);
assert boundValue != null;
final BoundType boundType =
serializableToCalcite(
BoundType.class,
upperNode.required(FIELD_NAME_BOUND_TYPE).asText());
final Range<?> r =
boundType == BoundType.OPEN ? lessThan(boundValue) : atMost(boundValue);
range = range.intersection(r);
}
if (range.hasUpperBound() || range.hasLowerBound()) {
builder.add(range);
}
}
// TODO: Since 1.18.0 nothing is serialized to FIELD_NAME_CONTAINS_NULL.
// This if condition (should be removed in future) is required for backward compatibility
// with Flink 1.17.x where FIELD_NAME_CONTAINS_NULL is still used.
final JsonNode containsNull = sargNode.get(FIELD_NAME_CONTAINS_NULL);
if (containsNull != null) {
return rexBuilder.makeSearchArgumentLiteral(
Sarg.of(containsNull.booleanValue(), builder.build()), relDataType);
}
final RexUnknownAs nullAs =
serializableToCalcite(
RexUnknownAs.class, sargNode.required(FIELD_NAME_NULL_AS).asText());
return rexBuilder.makeSearchArgumentLiteral(Sarg.of(nullAs, builder.build()), relDataType);
}
private static @Nullable Object deserializeLiteralValue(
JsonNode literalNode, SqlTypeName sqlTypeName, SerdeContext serdeContext) {
final JsonNode valueNode = literalNode.required(FIELD_NAME_VALUE);
if (valueNode.isNull()) {
return null;
}
switch (sqlTypeName) {
case BOOLEAN:
return valueNode.booleanValue();
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case FLOAT:
case DOUBLE:
case DECIMAL:
case INTERVAL_YEAR:
case INTERVAL_YEAR_MONTH:
case INTERVAL_MONTH:
case INTERVAL_DAY:
case INTERVAL_DAY_HOUR:
case INTERVAL_DAY_MINUTE:
case INTERVAL_DAY_SECOND:
case INTERVAL_HOUR:
case INTERVAL_HOUR_MINUTE:
case INTERVAL_HOUR_SECOND:
case INTERVAL_MINUTE:
case INTERVAL_MINUTE_SECOND:
case INTERVAL_SECOND:
return new BigDecimal(valueNode.asText());
case DATE:
return new DateString(valueNode.asText());
case TIME:
return new TimeString(valueNode.asText());
case TIMESTAMP:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
return new TimestampString(valueNode.asText());
case BINARY:
case VARBINARY:
return ByteString.ofBase64(valueNode.asText());
case CHAR:
case VARCHAR:
return serdeContext.getRexBuilder().makeLiteral(valueNode.asText()).getValue();
case SYMBOL:
final JsonNode symbolNode = literalNode.required(FIELD_NAME_SYMBOL);
final SerializableSymbol symbol =
SerializableSymbol.of(symbolNode.asText(), valueNode.asText());
return serializableToCalcite(symbol);
default:
throw new TableException("Unknown literal: " + valueNode);
}
}
private static RexNode deserializeFieldAccess(JsonNode jsonNode, SerdeContext serdeContext)
throws IOException {
final String fieldName = jsonNode.required(FIELD_NAME_NAME).asText();
final JsonNode exprNode = jsonNode.required(FIELD_NAME_EXPR);
final RexNode refExpr = deserialize(exprNode, serdeContext);
return serdeContext.getRexBuilder().makeFieldAccess(refExpr, fieldName, true);
}
private static RexNode deserializeCorrelVariable(JsonNode jsonNode, SerdeContext serdeContext) {
final String correl = jsonNode.required(FIELD_NAME_CORREL).asText();
final JsonNode logicalTypeNode = jsonNode.required(FIELD_NAME_TYPE);
final RelDataType fieldType =
RelDataTypeJsonDeserializer.deserialize(logicalTypeNode, serdeContext);
return serdeContext.getRexBuilder().makeCorrel(fieldType, new CorrelationId(correl));
}
private static RexNode deserializePatternFieldRef(
JsonNode jsonNode, SerdeContext serdeContext) {
final int inputIndex = jsonNode.required(FIELD_NAME_INPUT_INDEX).intValue();
final String alpha = jsonNode.required(FIELD_NAME_ALPHA).asText();
final JsonNode logicalTypeNode = jsonNode.required(FIELD_NAME_TYPE);
final RelDataType fieldType =
RelDataTypeJsonDeserializer.deserialize(logicalTypeNode, serdeContext);
return serdeContext.getRexBuilder().makePatternFieldRef(alpha, fieldType, inputIndex);
}
private static RexNode deserializeTableArgCall(JsonNode jsonNode, SerdeContext serdeContext) {
final JsonNode logicalTypeNode = jsonNode.required(FIELD_NAME_TYPE);
final RelDataType callType =
RelDataTypeJsonDeserializer.deserialize(logicalTypeNode, serdeContext);
final int inputIndex = jsonNode.required(FIELD_NAME_INPUT_INDEX).intValue();
final JsonNode partitionKeysNode = jsonNode.required(FIELD_NAME_PARTITION_KEYS);
final int[] partitionKeys = new int[partitionKeysNode.size()];
for (int i = 0; i < partitionKeysNode.size(); ++i) {
partitionKeys[i] = partitionKeysNode.get(i).asInt();
}
final JsonNode orderKeysNode = jsonNode.required(FIELD_NAME_ORDER_KEYS);
final int[] orderKeys = new int[orderKeysNode.size()];
for (int i = 0; i < orderKeysNode.size(); ++i) {
orderKeys[i] = orderKeysNode.get(i).asInt();
}
return new RexTableArgCall(callType, inputIndex, partitionKeys, orderKeys);
}
private static RexNode deserializeCall(JsonNode jsonNode, SerdeContext serdeContext)
throws IOException {
final SqlOperator operator = deserializeSqlOperator(jsonNode, serdeContext);
final ArrayNode operandNodes = (ArrayNode) jsonNode.get(FIELD_NAME_OPERANDS);
final List<RexNode> rexOperands = new ArrayList<>();
for (JsonNode node : operandNodes) {
rexOperands.add(deserialize(node, serdeContext));
}
final RelDataType callType;
if (jsonNode.has(FIELD_NAME_TYPE)) {
final JsonNode typeNode = jsonNode.get(FIELD_NAME_TYPE);
callType = RelDataTypeJsonDeserializer.deserialize(typeNode, serdeContext);
} else {
callType = serdeContext.getRexBuilder().deriveReturnType(operator, rexOperands);
}
return serdeContext.getRexBuilder().makeCall(callType, operator, rexOperands);
}
// --------------------------------------------------------------------------------------------
/** Logic shared with {@link AggregateCallJsonDeserializer}. */
static SqlOperator deserializeSqlOperator(JsonNode jsonNode, SerdeContext serdeContext) {
final SqlSyntax syntax;
if (jsonNode.has(FIELD_NAME_SYNTAX)) {
syntax =
serializableToCalcite(
SqlSyntax.class, jsonNode.required(FIELD_NAME_SYNTAX).asText());
} else {
syntax = SqlSyntax.FUNCTION;
}
if (jsonNode.has(FIELD_NAME_INTERNAL_NAME)) {
return deserializeInternalFunction(
jsonNode.required(FIELD_NAME_INTERNAL_NAME).asText(), syntax, serdeContext);
} else if (jsonNode.has(FIELD_NAME_CATALOG_NAME)) {
return deserializeCatalogFunction(jsonNode, syntax, serdeContext);
} else if (jsonNode.has(FIELD_NAME_CLASS)) {
return deserializeFunctionClass(jsonNode, serdeContext);
} else if (jsonNode.has(FIELD_NAME_SYSTEM_NAME)) {
return deserializeSystemFunction(
jsonNode.required(FIELD_NAME_SYSTEM_NAME).asText(), syntax, serdeContext);
} else if (jsonNode.has(FIELD_NAME_SQL_KIND)) {
return deserializeInternalFunction(
syntax, SqlKind.valueOf(jsonNode.get(FIELD_NAME_SQL_KIND).asText()));
} else {
throw new TableException("Invalid function call.");
}
}
private static SqlOperator deserializeSystemFunction(
String systemName, SqlSyntax syntax, SerdeContext serdeContext) {
// This method covers both temporary system functions and permanent system
// functions from a module
final Optional<SqlOperator> systemOperator =
lookupOptionalSqlOperator(
FunctionIdentifier.of(systemName), syntax, serdeContext, true);
if (systemOperator.isPresent()) {
return systemOperator.get();
}
throw missingSystemFunction(systemName);
}
private static SqlOperator deserializeInternalFunction(
String internalName, SqlSyntax syntax, SerdeContext serdeContext) {
// Try $FUNC$1
final Optional<SqlOperator> internalOperator =
lookupOptionalSqlOperator(
FunctionIdentifier.of(internalName), syntax, serdeContext, false);
if (internalOperator.isPresent()) {
return internalOperator.get();
}
// Try FUNC
final String publicName = BuiltInSqlOperator.extractNameFromQualifiedName(internalName);
final Optional<SqlOperator> latestOperator =
lookupOptionalSqlOperator(
FunctionIdentifier.of(publicName), syntax, serdeContext, true);
if (latestOperator.isPresent()) {
return latestOperator.get();
}
Optional<SqlOperator> sqlStdOperator =
lookupOptionalSqlStdOperator(publicName, syntax, null);
if (sqlStdOperator.isPresent()) {
return sqlStdOperator.get();
}
throw new TableException(
String.format(
"Could not resolve internal system function '%s'. "
+ "This is a bug, please file an issue.",
internalName));
}
private static SqlOperator deserializeInternalFunction(SqlSyntax syntax, SqlKind sqlKind) {
final Optional<SqlOperator> stdOperator = lookupOptionalSqlStdOperator("", syntax, sqlKind);
if (stdOperator.isPresent()) {
return stdOperator.get();
}
throw new TableException(
String.format(
"Could not resolve internal system function '%s'. "
+ "This is a bug, please file an issue.",
sqlKind.name()));
}
private static SqlOperator deserializeFunctionClass(
JsonNode jsonNode, SerdeContext serdeContext) {
final String className = jsonNode.required(FIELD_NAME_CLASS).asText();
final Class<?> functionClass = loadClass(className, serdeContext, "function");
final UserDefinedFunction functionInstance =
UserDefinedFunctionHelper.instantiateFunction(functionClass);
final ContextResolvedFunction resolvedFunction;
// This can never be a system function
// because we never serialize classes for system functions
if (jsonNode.has(FIELD_NAME_CATALOG_NAME)) {
final ObjectIdentifier objectIdentifier =
ObjectIdentifierJsonDeserializer.deserialize(
jsonNode.required(FIELD_NAME_CATALOG_NAME).asText(), serdeContext);
resolvedFunction =
ContextResolvedFunction.permanent(
FunctionIdentifier.of(objectIdentifier), functionInstance);
} else {
resolvedFunction = ContextResolvedFunction.anonymous(functionInstance);
}
switch (functionInstance.getKind()) {
case SCALAR:
case ASYNC_SCALAR:
case TABLE:
return BridgingSqlFunction.of(
serdeContext.getFlinkContext(),
serdeContext.getTypeFactory(),
resolvedFunction);
case AGGREGATE:
return BridgingSqlAggFunction.of(
serdeContext.getFlinkContext(),
serdeContext.getTypeFactory(),
resolvedFunction);
default:
throw new TableException(
String.format(
"Unsupported anonymous function kind '%s' for class '%s'.",
functionInstance.getKind(), className));
}
}
private static SqlOperator deserializeCatalogFunction(
JsonNode jsonNode, SqlSyntax syntax, SerdeContext serdeContext) {
final CatalogPlanRestore restoreStrategy =
serdeContext.getConfiguration().get(PLAN_RESTORE_CATALOG_OBJECTS);
final FunctionIdentifier identifier =
FunctionIdentifier.of(
ObjectIdentifierJsonDeserializer.deserialize(
jsonNode.required(FIELD_NAME_CATALOG_NAME).asText(), serdeContext));
switch (restoreStrategy) {
case ALL:
{
final Optional<SqlOperator> lookupOperator =
lookupOptionalSqlOperator(identifier, syntax, serdeContext, false);
if (lookupOperator.isPresent()) {
return lookupOperator.get();
} else if (jsonNode.has(FIELD_NAME_CLASS)) {
return deserializeFunctionClass(jsonNode, serdeContext);
}
throw missingFunctionFromCatalog(identifier, false);
}
case ALL_ENFORCED:
{
if (jsonNode.has(FIELD_NAME_CLASS)) {
return deserializeFunctionClass(jsonNode, serdeContext);
}
final Optional<SqlOperator> lookupOperator =
lookupOptionalSqlOperator(identifier, syntax, serdeContext, false);
if (lookupOperator.map(RexNodeJsonDeserializer::isTemporary).orElse(false)) {
return lookupOperator.get();
}
throw lookupDisabled(identifier);
}
case IDENTIFIER:
final Optional<SqlOperator> lookupOperator =
lookupOptionalSqlOperator(identifier, syntax, serdeContext, true);
if (lookupOperator.isPresent()) {
return lookupOperator.get();
} else {
throw missingFunctionFromCatalog(identifier, true);
}
default:
throw new TableException("Unsupported restore strategy: " + restoreStrategy);
}
}
private static boolean isTemporary(SqlOperator sqlOperator) {
if (sqlOperator instanceof BridgingSqlFunction) {
return ((BridgingSqlFunction) sqlOperator).getResolvedFunction().isTemporary();
} else if (sqlOperator instanceof BridgingSqlAggFunction) {
return ((BridgingSqlAggFunction) sqlOperator).getResolvedFunction().isTemporary();
}
return false;
}
private static Optional<SqlOperator> lookupOptionalSqlOperator(
FunctionIdentifier identifier,
SqlSyntax syntax,
SerdeContext serdeContext,
boolean throwOnError) {
final List<SqlOperator> foundOperators = new ArrayList<>();
try {
serdeContext
.getOperatorTable()
.lookupOperatorOverloads(
new SqlIdentifier(identifier.toList(), new SqlParserPos(0, 0)),
null, // category
syntax,
foundOperators,
SqlNameMatchers.liberal());
if (foundOperators.size() != 1) {
return Optional.empty();
}
return Optional.of(foundOperators.get(0));
} catch (Throwable t) {
if (throwOnError) {
throw new TableException(
String.format("Error during lookup of function '%s'.", identifier), t);
}
return Optional.empty();
}
}
private static Optional<SqlOperator> lookupOptionalSqlStdOperator(
String operatorName, SqlSyntax syntax, @Nullable SqlKind sqlKind) {
List<SqlOperator> foundOperators = new ArrayList<>();
// try to find operator from std operator table.
SqlStdOperatorTable.instance()
.lookupOperatorOverloads(
new SqlIdentifier(operatorName, new SqlParserPos(0, 0)),
null, // category
syntax,
foundOperators,
SqlNameMatchers.liberal());
if (foundOperators.size() == 1) {
return Optional.of(foundOperators.get(0));
}
// in case different operator has the same kind, check with both name and kind.
return foundOperators.stream()
.filter(o -> sqlKind != null && o.getKind() == sqlKind)
.findFirst();
}
private static TableException missingSystemFunction(String systemName) {
return new TableException(
String.format(
"Could not lookup system function '%s'. "
+ "Make sure it has been registered before because temporary "
+ "functions are not contained in the persisted plan. "
+ "If the function was provided by a module, make sure to reloaded "
+ "all used modules in the correct order.",
systemName));
}
private static TableException lookupDisabled(FunctionIdentifier identifier) {
return new TableException(
String.format(
"The persisted plan does not include all required catalog metadata for function '%s'. "
+ "However, lookup is disabled because option '%s' = '%s'. "
+ "Either enable the catalog lookup with '%s' = '%s' / '%s' or "
+ "regenerate the plan with '%s' != '%s'. "
+ "Make sure the function is not compiled as a temporary function.",
identifier.asSummaryString(),
PLAN_RESTORE_CATALOG_OBJECTS.key(),
CatalogPlanRestore.ALL_ENFORCED.name(),
PLAN_RESTORE_CATALOG_OBJECTS.key(),
IDENTIFIER.name(),
CatalogPlanRestore.ALL.name(),
PLAN_COMPILE_CATALOG_OBJECTS.key(),
CatalogPlanCompilation.IDENTIFIER.name()));
}
private static TableException missingFunctionFromCatalog(
FunctionIdentifier identifier, boolean forcedLookup) {
final String initialReason;
if (forcedLookup) {
initialReason =
String.format(
"Cannot resolve function '%s' and catalog lookup is forced because '%s' = '%s'. ",
identifier,
PLAN_RESTORE_CATALOG_OBJECTS.key(),
CatalogPlanRestore.IDENTIFIER);
} else {
initialReason =
String.format(
"Cannot resolve function '%s' and the persisted plan does not include "
+ "all required catalog function metadata. ",
identifier);
}
return new TableException(
initialReason
+ String.format(
"Make sure a registered catalog contains the function when restoring or "
+ "the function is available as a temporary function. "
+ "Otherwise regenerate the plan with '%s' != '%s' and make "
+ "sure the function was not compiled as a temporary function.",
PLAN_COMPILE_CATALOG_OBJECTS.key(),
CatalogPlanCompilation.IDENTIFIER.name()));
}
}
|
RexNodeJsonDeserializer
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCriteriaNodeBuilder.java
|
{
"start": 9111,
"end": 58297
}
|
class ____ implements NodeBuilder, Serializable {
private final String uuid;
private final String name;
private final transient JpaCompliance jpaCompliance;
private final transient QueryEngine queryEngine;
private final transient ValueHandlingMode criteriaValueHandlingMode;
private final transient ImmutableEntityUpdateQueryHandlingMode immutableEntityUpdateQueryHandlingMode;
private final transient BindingContext bindingContext;
private transient BasicType<Boolean> booleanType;
private transient BasicType<Integer> integerType;
private transient BasicType<Long> longType;
private transient BasicType<Character> characterType;
private transient BasicType<String> stringType;
private transient FunctionReturnTypeResolver sumReturnTypeResolver;
private transient FunctionReturnTypeResolver avgReturnTypeResolver;
private final transient Map<Class<? extends HibernateCriteriaBuilder>, HibernateCriteriaBuilder> extensions;
public SqmCriteriaNodeBuilder(
String uuid, String name,
QueryEngine queryEngine,
QueryEngineOptions options,
BindingContext bindingContext) {
this.queryEngine = queryEngine;
this.uuid = uuid;
this.name = name;
this.jpaCompliance = options.getJpaCompliance();
this.criteriaValueHandlingMode = options.getCriteriaValueHandlingMode();
this.immutableEntityUpdateQueryHandlingMode = options.getImmutableEntityUpdateQueryHandlingMode();
this.bindingContext = bindingContext;
this.extensions = loadExtensions();
}
private Map<Class<? extends HibernateCriteriaBuilder>, HibernateCriteriaBuilder> loadExtensions() {
// load registered criteria builder extensions
final Map<Class<? extends HibernateCriteriaBuilder>, HibernateCriteriaBuilder> extensions = new HashMap<>();
for ( CriteriaBuilderExtension extension : ServiceLoader.load( CriteriaBuilderExtension.class ) ) {
extensions.put( extension.getRegistrationKey(), extension.extend( this ) );
}
return extensions;
}
@Override
public JpaMetamodel getDomainModel() {
return bindingContext.getJpaMetamodel();
}
@Override
public TypeConfiguration getTypeConfiguration() {
return bindingContext.getTypeConfiguration();
}
@Override
public boolean isJpaQueryComplianceEnabled() {
return jpaCompliance.isJpaQueryComplianceEnabled();
}
@Override
public JpaCompliance getJpaCompliance() {
return jpaCompliance;
}
@Override @Deprecated
public ImmutableEntityUpdateQueryHandlingMode getImmutableEntityUpdateQueryHandlingMode() {
return immutableEntityUpdateQueryHandlingMode;
}
@Override
public boolean allowImmutableEntityUpdate() {
return immutableEntityUpdateQueryHandlingMode != ImmutableEntityUpdateQueryHandlingMode.EXCEPTION;
}
@Override
public BasicType<Boolean> getBooleanType() {
final BasicType<Boolean> booleanType = this.booleanType;
if ( booleanType == null ) {
return this.booleanType =
getTypeConfiguration().getBasicTypeRegistry()
.resolve( StandardBasicTypes.BOOLEAN );
}
return booleanType;
}
@Override
public BasicType<Integer> getIntegerType() {
final BasicType<Integer> integerType = this.integerType;
if ( integerType == null ) {
return this.integerType =
getTypeConfiguration().getBasicTypeRegistry()
.resolve( StandardBasicTypes.INTEGER );
}
return integerType;
}
@Override
public BasicType<Long> getLongType() {
final BasicType<Long> longType = this.longType;
if ( longType == null ) {
return this.longType =
getTypeConfiguration().getBasicTypeRegistry()
.resolve( StandardBasicTypes.LONG );
}
return longType;
}
@Override
public BasicType<Character> getCharacterType() {
final BasicType<Character> characterType = this.characterType;
if ( characterType == null ) {
return this.characterType =
getTypeConfiguration().getBasicTypeRegistry()
.resolve( StandardBasicTypes.CHARACTER );
}
return characterType;
}
@Override
public BasicType<String> getStringType() {
final BasicType<String> stringType = this.stringType;
if ( stringType == null ) {
return this.stringType =
getTypeConfiguration().getBasicTypeRegistry()
.resolve( StandardBasicTypes.STRING );
}
return stringType;
}
public FunctionReturnTypeResolver getSumReturnTypeResolver() {
final FunctionReturnTypeResolver resolver = sumReturnTypeResolver;
if ( resolver == null ) {
return this.sumReturnTypeResolver = new SumReturnTypeResolver( getTypeConfiguration() );
}
return resolver;
}
public FunctionReturnTypeResolver getAvgReturnTypeResolver() {
final FunctionReturnTypeResolver resolver = avgReturnTypeResolver;
if ( resolver == null ) {
return this.avgReturnTypeResolver = new AvgFunction.ReturnTypeResolver( getTypeConfiguration() );
}
return resolver;
}
@Override
public QueryEngine getQueryEngine() {
return queryEngine;
}
@Override
public JpaMetamodel getJpaMetamodel() {
return bindingContext.getJpaMetamodel();
}
@Override
public SqmSelectStatement<Object> createQuery() {
// IMPORTANT: we want to pass null here for the result-type
// to indicate that we do not know. this will allow later
// calls to `SqmSelectStatement#select`, `SqmSelectStatement#multiSelect`,
// etc. to influence the result type
return new SqmSelectStatement<>( Object.class, this );
}
@Override
public <T> SqmSelectStatement<T> createQuery(Class<T> resultClass) {
return new SqmSelectStatement<>( resultClass, this );
}
@Override
public <T> SqmSelectStatement<T> createQuery(String hql, Class<T> resultClass) {
final SqmStatement<T> statement =
queryEngine.getHqlTranslator().translate( hql, resultClass );
if ( statement instanceof SqmSelectStatement ) {
return new SqmSelectStatement<>( (SqmSelectStatement<T>) statement );
}
else {
throw new IllegalArgumentException("Not a 'select' statement");
}
}
@Override
public SqmSelectStatement<Tuple> createTupleQuery() {
return new SqmSelectStatement<>( Tuple.class, this );
}
@Override
public <T> SqmUpdateStatement<T> createCriteriaUpdate(Class<T> targetEntity) {
return new SqmUpdateStatement<>( targetEntity, this );
}
@Override
public <T> SqmDeleteStatement<T> createCriteriaDelete(Class<T> targetEntity) {
return new SqmDeleteStatement<>( targetEntity, this );
}
@Override
public <T> SqmInsertValuesStatement<T> createCriteriaInsertValues(Class<T> targetEntity) {
return new SqmInsertValuesStatement<>( targetEntity, this );
}
@Override
public <T> SqmInsertSelectStatement<T> createCriteriaInsertSelect(Class<T> targetEntity) {
return new SqmInsertSelectStatement<>( targetEntity, this );
}
@Override
public SqmValues values(Expression<?>... expressions) {
return values( asList( expressions ) );
}
@Override
public SqmValues values(List<? extends Expression<?>> expressions) {
//noinspection unchecked
return new SqmValues( (List<SqmExpression<?>>) expressions );
}
@Override
public <T> JpaCriteriaQuery<T> union(boolean all, CriteriaQuery<? extends T> query1, CriteriaQuery<?>... queries) {
return setOperation( all ? SetOperator.UNION_ALL : SetOperator.UNION, query1, queries );
}
@Override
public <T> JpaCriteriaQuery<T> intersect(boolean all, CriteriaQuery<? extends T> query1, CriteriaQuery<?>... queries) {
return setOperation( all ? SetOperator.INTERSECT_ALL : SetOperator.INTERSECT, query1, queries );
}
@Override
public <T> JpaCriteriaQuery<T> except(boolean all, CriteriaQuery<? extends T> query1, CriteriaQuery<?>... queries) {
return setOperation( all ? SetOperator.EXCEPT_ALL : SetOperator.EXCEPT, query1, queries );
}
@Override
public <T> JpaCriteriaSelect<T> union(CriteriaSelect<? extends T> left, CriteriaSelect<? extends T> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.UNION, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.UNION, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@Override
public <T> JpaSubQuery<T> union(boolean all, Subquery<? extends T> query1, Subquery<?>... queries) {
return setOperation( all ? SetOperator.UNION_ALL : SetOperator.UNION, query1, queries );
}
@Override
public <T> CriteriaSelect<T> unionAll(CriteriaSelect<? extends T> left, CriteriaSelect<? extends T> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.UNION_ALL, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.UNION_ALL, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@Override
public <T> JpaSubQuery<T> intersect(boolean all, Subquery<? extends T> query1, Subquery<?>... queries) {
return setOperation( all ? SetOperator.INTERSECT_ALL : SetOperator.INTERSECT, query1, queries );
}
@Override
public <T> CriteriaSelect<T> except(CriteriaSelect<T> left, CriteriaSelect<?> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.EXCEPT, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.EXCEPT, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@Override
public <T> CriteriaSelect<T> exceptAll(CriteriaSelect<T> left, CriteriaSelect<?> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.EXCEPT_ALL, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.EXCEPT_ALL, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@Override
public <T> JpaSubQuery<T> except(boolean all, Subquery<? extends T> query1, Subquery<?>... queries) {
return setOperation( all ? SetOperator.EXCEPT_ALL : SetOperator.EXCEPT, query1, queries );
}
@SuppressWarnings("unchecked")
private <T> JpaCriteriaQuery<T> setOperation(
SetOperator operator,
CriteriaQuery<? extends T> criteriaQuery,
CriteriaQuery<?>... queries) {
final Class<T> resultType = (Class<T>) criteriaQuery.getResultType();
final List<SqmQueryPart<T>> queryParts = new ArrayList<>( queries.length + 1 );
final Map<String, SqmCteStatement<?>> cteStatements = new LinkedHashMap<>();
final SqmSelectStatement<T> selectStatement = (SqmSelectStatement<T>) criteriaQuery;
collectQueryPartsAndCtes( selectStatement, queryParts, cteStatements );
for ( CriteriaQuery<?> query : queries ) {
if ( query.getResultType() != resultType ) {
throw new IllegalArgumentException( "Result type of all operands must match" );
}
collectQueryPartsAndCtes( (SqmSelectQuery<T>) query, queryParts, cteStatements );
}
return new SqmSelectStatement<>(
new SqmQueryGroup<>( this, operator, queryParts ),
resultType,
cteStatements,
selectStatement.getQuerySource(),
this
);
}
@SuppressWarnings("unchecked")
private <T> JpaSubQuery<T> setOperation(
SetOperator operator,
Subquery<? extends T> subquery,
Subquery<?>... queries) {
final Class<T> resultType = (Class<T>) subquery.getResultType();
final SqmQuery<T> parent = (SqmQuery<T>) subquery.getParent();
final List<SqmQueryPart<T>> queryParts = new ArrayList<>( queries.length + 1 );
final Map<String, SqmCteStatement<?>> cteStatements = new LinkedHashMap<>();
collectQueryPartsAndCtes( (SqmSelectQuery<T>) subquery, queryParts, cteStatements );
for ( Subquery<?> query : queries ) {
if ( query.getResultType() != resultType ) {
throw new IllegalArgumentException( "Result type of all operands must match" );
}
if ( query.getParent() != parent ) {
throw new IllegalArgumentException( "Subquery parent of all operands must match" );
}
collectQueryPartsAndCtes( (SqmSelectQuery<T>) query, queryParts, cteStatements );
}
return new SqmSubQuery<>(
parent,
new SqmQueryGroup<>( this, operator, queryParts ),
resultType,
cteStatements,
this
);
}
private <T> void collectQueryPartsAndCtes(
SqmSelectQuery<T> query,
List<SqmQueryPart<T>> queryParts,
Map<String, SqmCteStatement<?>> cteStatements) {
queryParts.add( query.getQueryPart() );
for ( SqmCteStatement<?> cteStatement : query.getCteStatements() ) {
final String name = cteStatement.getCteTable().getCteName();
final SqmCteStatement<?> old = cteStatements.put( name, cteStatement );
if ( old != null && old != cteStatement ) {
throw new IllegalArgumentException(
String.format( "Different CTE with same name [%s] found in different set operands!", name )
);
}
}
}
@Override
public <X, T> SqmExpression<X> cast(JpaExpression<T> expression, Class<X> castTargetJavaType) {
return cast( expression, castTarget( castTargetJavaType ) );
}
@Override
public <X, T> SqmExpression<X> cast(JpaExpression<T> expression, JpaCastTarget<X> castTarget) {
final SqmCastTarget<X> sqmCastTarget = (SqmCastTarget<X>) castTarget;
return getFunctionDescriptor( "cast" ).generateSqmExpression(
asList( (SqmTypedNode<?>) expression, sqmCastTarget ),
sqmCastTarget.getType(),
queryEngine
);
}
@Override
public <X> SqmCastTarget<X> castTarget(Class<X> castTargetJavaType) {
return castTarget( castTargetJavaType, null, null, null );
}
@Override
public <X> SqmCastTarget<X> castTarget(Class<X> castTargetJavaType, long length) {
return castTarget( castTargetJavaType, length, null, null );
}
@Override
public <X> SqmCastTarget<X> castTarget(Class<X> castTargetJavaType, int precision, int scale) {
return castTarget( castTargetJavaType, null, precision, scale );
}
private <X> SqmCastTarget<X> castTarget(Class<X> castTargetJavaType, @Nullable Long length, @Nullable Integer precision, @Nullable Integer scale) {
final BasicType<X> type = getTypeConfiguration().standardBasicTypeForJavaType( castTargetJavaType );
return new SqmCastTarget<>( type, length, precision, scale, this );
}
@Override
public SqmPredicate wrap(Expression<Boolean> expression) {
return expression instanceof SqmPredicate predicate
? predicate
: new SqmBooleanExpressionPredicate( (SqmExpression<Boolean>) expression, this );
}
@Override
@SafeVarargs
public final SqmPredicate wrap(Expression<Boolean>... expressions) {
if ( expressions.length == 1 ) {
return wrap( expressions[0] );
}
final List<SqmPredicate> predicates = new ArrayList<>( expressions.length );
for ( Expression<Boolean> expression : expressions ) {
predicates.add( wrap( expression ) );
}
return new SqmJunctionPredicate( Predicate.BooleanOperator.AND, predicates, this );
}
@Override
public SqmPredicate wrap(List<? extends Expression<Boolean>> restrictions) {
if ( restrictions.size() == 1 ) {
return wrap( restrictions.get( 0 ) );
}
final List<SqmPredicate> predicates = new ArrayList<>( restrictions.size() );
for ( Expression<Boolean> expression : restrictions ) {
predicates.add( wrap( expression ) );
}
return new SqmJunctionPredicate( Predicate.BooleanOperator.AND, predicates, this );
}
@Override @SuppressWarnings("unchecked")
public <T extends HibernateCriteriaBuilder> T unwrap(Class<T> clazz) {
final T result = (T) extensions.get( clazz );
if ( result == null ) {
throw new IllegalArgumentException( "Unable to unwrap to " + clazz.getName() );
}
return result;
}
@Override
public SqmPath<?> fk(Path<?> path) {
final SqmPath<?> sqmPath = (SqmPath<?>) path;
final SqmPathSource<?> toOneReference = sqmPath.getReferencedPathSource();
final boolean validToOneRef =
toOneReference.getBindableType() == Bindable.BindableType.SINGULAR_ATTRIBUTE
&& toOneReference instanceof EntitySqmPathSource;
if ( !validToOneRef ) {
throw new FunctionArgumentException(
String.format(
Locale.ROOT,
"Argument '%s' of 'fk()' function is not a single-valued association",
sqmPath.getNavigablePath()
)
);
}
return new SqmFkExpression<>( sqmPath );
}
@Override
public <X, T extends X> SqmPath<T> treat(Path<X> path, Class<T> type) {
return ( (SqmPath<X>) path ).treatAs( type );
}
@Override
public <X, T extends X> SqmRoot<T> treat(Root<X> root, Class<T> type) {
//noinspection unchecked
return (SqmTreatedRoot) ( (SqmRoot<X>) root ).treatAs( type );
}
@Override
public <T> JpaCriteriaQuery<T> union(CriteriaQuery<? extends T> left, CriteriaQuery<? extends T> right) {
return createUnionSet( SetOperator.UNION, left, right );
}
@Override
public <T> JpaCriteriaQuery<T> unionAll(CriteriaQuery<? extends T> left, CriteriaQuery<? extends T> right) {
return createUnionSet( SetOperator.UNION_ALL, left, right );
}
@Override
public <T> CriteriaSelect<T> intersect(CriteriaSelect<? super T> left, CriteriaSelect<? super T> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.INTERSECT, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.INTERSECT, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@Override
public <T> CriteriaSelect<T> intersectAll(CriteriaSelect<? super T> left, CriteriaSelect<? super T> right) {
if ( left instanceof Subquery<?> ) {
assert right instanceof Subquery<?>;
//noinspection unchecked
return setOperation( SetOperator.INTERSECT_ALL, (Subquery<T>) left, (Subquery<T>) right );
}
//noinspection unchecked
return setOperation( SetOperator.INTERSECT_ALL, (JpaCriteriaQuery<T>) left, (JpaCriteriaQuery<T>) right );
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> JpaCriteriaQuery<T> createUnionSet(
SetOperator operator,
CriteriaQuery<? extends T> left,
CriteriaQuery<? extends T> right) {
assert operator == SetOperator.UNION || operator == SetOperator.UNION_ALL;
final SqmSelectStatement<? extends T> leftSqm = (SqmSelectStatement<? extends T>) left;
final SqmSelectStatement<? extends T> rightSqm = (SqmSelectStatement<? extends T>) right;
// SqmQueryGroup is the UNION ALL between the two
final SqmQueryGroup sqmQueryGroup = new SqmQueryGroup(
leftSqm.nodeBuilder(),
operator,
List.of( leftSqm.getQueryPart(), rightSqm.getQueryPart() )
);
final SqmSelectStatement sqmSelectStatement = new SqmSelectStatement<>(
leftSqm.getResultType(),
SqmQuerySource.CRITERIA,
leftSqm.nodeBuilder()
);
sqmSelectStatement.setQueryPart( sqmQueryGroup );
return sqmSelectStatement;
}
@Override
public <T> JpaCriteriaQuery<T> intersect(CriteriaQuery<? super T> left, CriteriaQuery<? super T> right) {
return createIntersectSet( SetOperator.INTERSECT, left, right );
}
@Override
public <T> JpaCriteriaQuery<T> intersectAll(CriteriaQuery<? super T> left, CriteriaQuery<? super T> right) {
return createIntersectSet( SetOperator.INTERSECT_ALL, left, right );
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> JpaCriteriaQuery<T> createIntersectSet(
SetOperator operator,
CriteriaQuery<? super T> left,
CriteriaQuery<? super T> right) {
assert operator == SetOperator.INTERSECT || operator == SetOperator.INTERSECT_ALL;
final SqmSelectStatement<? extends T> leftSqm = (SqmSelectStatement<? extends T>) left;
final SqmSelectStatement<? extends T> rightSqm = (SqmSelectStatement<? extends T>) right;
// SqmQueryGroup is the UNION ALL between the two
final SqmQueryGroup sqmQueryGroup = new SqmQueryGroup(
leftSqm.nodeBuilder(),
operator,
List.of( leftSqm.getQueryPart(), rightSqm.getQueryPart() )
);
final SqmSelectStatement sqmSelectStatement = new SqmSelectStatement<>(
leftSqm.getResultType(),
SqmQuerySource.CRITERIA,
leftSqm.nodeBuilder()
);
sqmSelectStatement.setQueryPart( sqmQueryGroup );
return sqmSelectStatement;
}
@Override
public <T> JpaCriteriaQuery<T> except(CriteriaQuery<T> left, CriteriaQuery<?> right) {
return createExceptSet( SetOperator.EXCEPT, left, right );
}
@Override
public <T> JpaCriteriaQuery<T> exceptAll(CriteriaQuery<T> left, CriteriaQuery<?> right) {
return createExceptSet( SetOperator.EXCEPT_ALL, left, right );
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> JpaCriteriaQuery<T> createExceptSet(
SetOperator operator,
CriteriaQuery<T> left,
CriteriaQuery<?> right) {
assert operator == SetOperator.EXCEPT || operator == SetOperator.EXCEPT_ALL;
final SqmSelectStatement<? extends T> leftSqm = (SqmSelectStatement<? extends T>) left;
final SqmSelectStatement<? extends T> rightSqm = (SqmSelectStatement<? extends T>) right;
// SqmQueryGroup is the UNION ALL between the two
final SqmQueryGroup sqmQueryGroup = new SqmQueryGroup(
leftSqm.nodeBuilder(),
operator,
List.of( leftSqm.getQueryPart(), rightSqm.getQueryPart() )
);
final SqmSelectStatement sqmSelectStatement = new SqmSelectStatement<>(
leftSqm.getResultType(),
SqmQuerySource.CRITERIA,
leftSqm.nodeBuilder()
);
sqmSelectStatement.setQueryPart( sqmQueryGroup );
return sqmSelectStatement;
}
@Override
public <X, T, V extends T> SqmSingularJoin<X, V> treat(Join<X, T> join, Class<V> type) {
return (SqmTreatedSingularJoin<X,T,V>) ( (SqmSingularJoin<X, T>) join ).treatAs( type );
}
@Override
public <X, T, E extends T> SqmBagJoin<X, E> treat(CollectionJoin<X, T> join, Class<E> type) {
return ( (SqmBagJoin<X, T>) join ).treatAs( type );
}
@Override
public <X, T, E extends T> SqmSetJoin<X, E> treat(SetJoin<X, T> join, Class<E> type) {
return ( (SqmSetJoin<X, T>) join ).treatAs( type );
}
@Override
public <X, T, E extends T> SqmListJoin<X, E> treat(ListJoin<X, T> join, Class<E> type) {
return ( (SqmListJoin<X, T>) join ).treatAs( type );
}
@Override
public <X, K, T, V extends T> SqmMapJoin<X, K, V> treat(MapJoin<X, K, T> join, Class<V> type) {
return ( (SqmMapJoin<X, K, T>) join ).treatAs( type );
}
@Override
public SqmSortSpecification sort(JpaExpression<?> sortExpression, SortDirection sortOrder, Nulls nullPrecedence) {
return new SqmSortSpecification( (SqmExpression<?>) sortExpression, sortOrder, nullPrecedence );
}
@Override
public SqmSortSpecification sort(
JpaExpression<?> sortExpression,
SortDirection sortOrder,
Nulls nullPrecedence,
boolean ignoreCase) {
return new SqmSortSpecification( (SqmExpression<?>) sortExpression, sortOrder, nullPrecedence, ignoreCase );
}
@Override
public SqmSortSpecification sort(JpaExpression<?> sortExpression, SortDirection sortOrder) {
return new SqmSortSpecification( (SqmExpression<?>) sortExpression, sortOrder );
}
@Override
public SqmSortSpecification sort(JpaExpression<?> sortExpression) {
return new SqmSortSpecification( (SqmExpression<?>) sortExpression );
}
@Override
public SqmSortSpecification asc(Expression<?> x) {
return new SqmSortSpecification( (SqmExpression<?>) x, SortDirection.ASCENDING );
}
@Override
public SqmSortSpecification desc(Expression<?> x) {
return new SqmSortSpecification( (SqmExpression<?>) x, SortDirection.DESCENDING );
}
@Override
public Order asc(Expression<?> expression, Nulls nullPrecedence) {
return new SqmSortSpecification( (SqmExpression<?>) expression, SortDirection.ASCENDING, nullPrecedence );
}
@Override
public Order desc(Expression<?> expression, Nulls nullPrecedence) {
return new SqmSortSpecification( (SqmExpression<?>) expression, SortDirection.DESCENDING, nullPrecedence );
}
@Override
public JpaOrder asc(Expression<?> x, boolean nullsFirst) {
return new SqmSortSpecification(
(SqmExpression<?>) x,
SortDirection.ASCENDING,
nullsFirst ? Nulls.FIRST : Nulls.LAST
);
}
@Override
public JpaOrder desc(Expression<?> x, boolean nullsFirst) {
return new SqmSortSpecification(
(SqmExpression<?>) x,
SortDirection.DESCENDING,
nullsFirst ? Nulls.FIRST : Nulls.LAST
);
}
@Override
public JpaSearchOrder search(JpaCteCriteriaAttribute sortExpression, SortDirection sortOrder, Nulls nullPrecedence) {
return new SqmSearchClauseSpecification( (SqmCteTableColumn) sortExpression, sortOrder, nullPrecedence );
}
@Override
public JpaSearchOrder search(JpaCteCriteriaAttribute sortExpression, SortDirection sortOrder) {
return new SqmSearchClauseSpecification( (SqmCteTableColumn) sortExpression, sortOrder, Nulls.NONE );
}
@Override
public JpaSearchOrder search(JpaCteCriteriaAttribute sortExpression) {
return new SqmSearchClauseSpecification( (SqmCteTableColumn) sortExpression, SortDirection.ASCENDING, Nulls.NONE );
}
@Override
public JpaSearchOrder asc(JpaCteCriteriaAttribute x) {
return new SqmSearchClauseSpecification( (SqmCteTableColumn) x, SortDirection.ASCENDING, Nulls.NONE );
}
@Override
public JpaSearchOrder desc(JpaCteCriteriaAttribute x) {
return new SqmSearchClauseSpecification( (SqmCteTableColumn) x, SortDirection.DESCENDING, Nulls.NONE );
}
@Override
public JpaSearchOrder asc(JpaCteCriteriaAttribute x, boolean nullsFirst) {
return new SqmSearchClauseSpecification(
(SqmCteTableColumn) x,
SortDirection.ASCENDING,
nullsFirst ? Nulls.FIRST : Nulls.LAST
);
}
@Override
public JpaSearchOrder desc(JpaCteCriteriaAttribute x, boolean nullsFirst) {
return new SqmSearchClauseSpecification(
(SqmCteTableColumn) x,
SortDirection.DESCENDING,
nullsFirst ? Nulls.FIRST : Nulls.LAST
);
}
@Override
public JpaCompoundSelection<Tuple> tuple(Selection<?>... selections) {
return tuple( asList( selections ) );
}
@Override
public JpaCompoundSelection<Tuple> tuple(List<Selection<?>> selections) {
checkMultiselect( selections );
return new SqmJpaCompoundSelection<>(
selections.stream().map( selection -> (SqmSelectableNode<?>) selection ).toList(),
getTypeConfiguration().getJavaTypeRegistry().resolveDescriptor( Tuple.class ),
this
);
}
@Override @Deprecated(since = "7", forRemoval = true)
public <R> SqmTuple<R> tuple(Class<R> tupleType, SqmExpression<?>... expressions) {
return tuple( tupleType, asList( expressions ) );
}
@Override @Deprecated(since = "7", forRemoval = true)
public <R> SqmTuple<R> tuple(SqmExpressible<R> tupleType, SqmExpression<?>... expressions) {
return tuple( tupleType, asList( expressions ) );
}
@Override @Deprecated(since = "7", forRemoval = true)
public <R> SqmTuple<R> tuple(Class<R> tupleType, List<? extends SqmExpression<?>> expressions) {
@SuppressWarnings("unchecked")
final SqmExpressible<R> expressibleType =
tupleType == null || tupleType == Object[].class
? (SqmDomainType<R>) getTypeConfiguration().resolveTupleType( expressions )
: (SqmEmbeddableDomainType<R>) getDomainModel().embeddable( tupleType );
return tuple( expressibleType, expressions );
}
@Override @Deprecated(since = "7", forRemoval = true)
public <R> SqmTuple<R> tuple(SqmExpressible<R> tupleType, List<? extends SqmExpression<?>> sqmExpressions) {
if ( tupleType == null ) {
//noinspection unchecked
tupleType = (SqmDomainType<R>) getTypeConfiguration().resolveTupleType( sqmExpressions );
}
return new SqmTuple<>( new ArrayList<>( sqmExpressions ), (SqmBindableType<R>) tupleType, this );
}
@Override
public JpaCompoundSelection<Object[]> array(Selection<?>... selections) {
return array( Object[].class,
Arrays.stream( selections ).map( selection -> (SqmSelectableNode<?>) selection ).toList() );
}
@Override
public JpaCompoundSelection<Object[]> array(List<Selection<?>> selections) {
return arrayInternal( Object[].class,
selections.stream().map( selection -> (SqmSelectableNode<?>) selection ).toList() );
}
@Override
public <Y> JpaCompoundSelection<Y> array(Class<Y> resultClass, Selection<?>... selections) {
return arrayInternal( resultClass,
Arrays.stream( selections ).map( selection -> (SqmSelectableNode<?>) selection ).toList() );
}
@Override
public <Y> JpaCompoundSelection<Y> array(Class<Y> resultClass, List<? extends Selection<?>> selections) {
return arrayInternal( resultClass,
selections.stream().map( selection -> (SqmSelectableNode<?>) selection ).toList() );
}
public <Y> JpaCompoundSelection<Y> arrayInternal(Class<Y> resultClass, List<? extends SqmSelectableNode<?>> selections) {
checkMultiselect( selections );
final var javaType = getTypeConfiguration().getJavaTypeRegistry().resolveDescriptor( resultClass );
return new SqmJpaCompoundSelection<>( selections, javaType, this );
}
@Override
public <Y> JpaCompoundSelection<Y> construct(Class<Y> resultClass, Selection<?>... arguments) {
return constructInternal( resultClass,
Arrays.stream( arguments ).map( arg -> (SqmSelectableNode<?>) arg ).toList() );
}
@Override
public <Y> JpaCompoundSelection<Y> construct(Class<Y> resultClass, List<? extends Selection<?>> arguments) {
return constructInternal( resultClass,
arguments.stream().map( arg -> (SqmSelectableNode<?>) arg ).toList() );
}
@SuppressWarnings("unchecked")
private <Y> JpaCompoundSelection<Y> constructInternal(Class<Y> resultClass, List<? extends SqmSelectableNode<?>> arguments) {
checkMultiselect( arguments );
if ( List.class.equals( resultClass ) ) {
return (SqmDynamicInstantiation<Y>) listInstantiation( arguments, this );
}
else if ( Map.class.equals( resultClass ) ) {
return (SqmDynamicInstantiation<Y>) mapInstantiation( arguments, this );
}
else {
return classInstantiation( resultClass, arguments, this );
}
}
/**
* Check the arguments of {@link jakarta.persistence.criteria.CriteriaBuilder#array},
* {@link jakarta.persistence.criteria.CriteriaBuilder#construct}, or
* {@link jakarta.persistence.criteria.CriteriaBuilder#tuple}.
*
* @param selections The selection varargs to check
*
* @throws IllegalArgumentException If the selection items are not valid per
* according to {@linkplain CriteriaQuery#multiselect this documentation}.
* <i>"An argument to the multiselect method must not be a tuple-
* or array-valued compound selection item."</i>
*/
private void checkMultiselect(List<? extends Selection<?>> selections) {
final HashSet<String> aliases = new HashSet<>( determineProperSizing( selections.size() ) );
for ( Selection<?> selection : selections ) {
if ( selection.isCompoundSelection() ) {
final Class<?> javaType = selection.getJavaType();
if ( javaType.isArray() ) {
throw new IllegalArgumentException(
"Selection item in a multi-select cannot contain compound array-valued elements"
);
}
if ( Tuple.class.isAssignableFrom( javaType ) ) {
throw new IllegalArgumentException(
"Selection item in a multi-select cannot contain compound tuple-valued elements"
);
}
}
final String alias = selection.getAlias();
if ( StringHelper.isNotEmpty( alias ) && !aliases.add( alias ) ) {
throw new IllegalArgumentException( "Multi-select expressions have duplicate alias '" + alias + "'" );
}
}
}
@Override
public <N extends Number> SqmExpression<Double> avg(Expression<N> argument) {
return getFunctionDescriptor( "avg" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
@SuppressWarnings("unchecked")
public <N extends Number> SqmExpression<N> sum(Expression<N> argument) {
final SqmTypedNode<N> typedNode = (SqmTypedNode<N>) argument;
return getFunctionDescriptor( "sum" ).generateSqmExpression(
typedNode,
(ReturnableType<N>) typedNode.getExpressible().getSqmType(),
queryEngine
);
}
@Override
public SqmExpression<Long> sumAsLong(Expression<Integer> argument) {
return getFunctionDescriptor( "sum" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
public SqmExpression<Double> sumAsDouble(Expression<Float> argument) {
return getFunctionDescriptor( "sum" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
public <N extends Number> SqmExpression<N> max(Expression<N> argument) {
return getFunctionDescriptor( "max" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
public <N extends Number> SqmExpression<N> min(Expression<N> argument) {
return getFunctionDescriptor( "min" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
public <X extends Comparable<? super X>> SqmExpression<X> greatest(Expression<X> argument) {
return queryEngine.getSqmFunctionRegistry().findFunctionDescriptor( "max" )
.generateSqmExpression( (SqmTypedNode<?>) argument, null, queryEngine);
}
@Override
public <X extends Comparable<? super X>> SqmExpression<X> least(Expression<X> argument) {
return queryEngine.getSqmFunctionRegistry().findFunctionDescriptor( "min" )
.generateSqmExpression( (SqmTypedNode<?>) argument, null, queryEngine);
}
@Override
public SqmExpression<Long> count(Expression<?> argument) {
return getFunctionDescriptor( "count" ).generateSqmExpression(
(SqmTypedNode<?>) argument,
null,
queryEngine
);
}
@Override
public SqmExpression<Long> countDistinct(Expression<?> argument) {
return getFunctionDescriptor( "count" ).generateSqmExpression(
new SqmDistinct<>( (SqmExpression<?>) argument, this ),
null,
queryEngine
);
}
@Override
public SqmExpression<Long> count() {
return getFunctionDescriptor( "count" ).generateSqmExpression(
new SqmStar( this ),
null,
queryEngine
);
}
@Override
public JpaExpression<Integer> sign(Expression<? extends Number> x) {
return getFunctionDescriptor( "sign" ).generateSqmExpression(
(SqmExpression<?>) x,
null,
queryEngine
);
}
@Override
public <N extends Number> JpaExpression<N> ceiling(Expression<N> x) {
return getFunctionDescriptor( "ceiling" ).generateSqmExpression(
(SqmExpression<?>) x,
null,
queryEngine
);
}
@Override
public <N extends Number> JpaExpression<N> floor(Expression<N> x) {
return getFunctionDescriptor( "floor" ).generateSqmExpression(
(SqmExpression<?>) x,
null,
queryEngine
);
}
@Override
public JpaExpression<Double> exp(Expression<? extends Number> x) {
return getFunctionDescriptor( "exp" ).generateSqmExpression(
(SqmExpression<?>) x,
null,
queryEngine
);
}
@Override
public JpaExpression<Double> ln(Expression<? extends Number> x) {
return getFunctionDescriptor( "ln" ).generateSqmExpression(
(SqmExpression<?>) x,
null,
queryEngine
);
}
@Override
public JpaExpression<Double> power(Expression<? extends Number> x, Expression<? extends Number> y) {
return getFunctionDescriptor( "power" ).generateSqmExpression(
asList( (SqmExpression<?>) x, (SqmExpression<?>) y),
null,
queryEngine
);
}
@Override
public JpaExpression<Double> power(Expression<? extends Number> x, Number y) {
return getFunctionDescriptor( "power" ).generateSqmExpression(
asList( (SqmExpression<?>) x, value( y ) ),
null,
queryEngine
);
}
@Override
public <T extends Number> JpaExpression<T> round(Expression<T> x, Integer n) {
return getFunctionDescriptor( "round" ).generateSqmExpression(
asList( (SqmExpression<?>) x, value( n ) ),
null,
queryEngine
);
}
@Override
public <T extends Number> JpaExpression<T> truncate(Expression<T> x, Integer n) {
return getFunctionDescriptor( "truncate" ).generateSqmExpression(
asList( (SqmExpression<?>) x, value( n ) ),
null,
queryEngine
);
}
@Override
public <N extends Number> SqmExpression<N> neg(Expression<N> x) {
final SqmExpression<N> sqmExpression = (SqmExpression<N>) x;
return new SqmUnaryOperation<>(
UnaryArithmeticOperator.UNARY_MINUS,
sqmExpression,
getNodeBuilder()
);
}
@Override
public <N extends Number> SqmExpression<N> abs(Expression<N> x) {
return getFunctionDescriptor( "abs" ).generateSqmExpression(
(SqmTypedNode<?>) x,
null,
queryEngine
);
}
@Override
public JpaExpression<Duration> duration(long magnitude, TemporalUnit unit) {
return new SqmToDuration<>(
literal( magnitude ),
new SqmDurationUnit<>( unit, getLongType(), this ),
getTypeConfiguration().standardBasicTypeForJavaType( Duration.class ),
this
);
}
@Override
public JpaExpression<Long> durationByUnit(TemporalUnit unit, Expression<Duration> duration) {
return new SqmByUnit(
new SqmDurationUnit<>( unit, getLongType(), this ),
(SqmExpression<Duration>) duration,
getLongType(),
this
);
}
@Override
public JpaExpression<Duration> durationSum(Expression<Duration> x, Expression<Duration> y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
(SqmExpression<Duration>) x, (SqmExpression<Duration>) y );
}
@Override
public JpaExpression<Duration> durationSum(Expression<Duration> x, Duration y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
(SqmExpression<Duration>) x, value( y ) );
}
@Override
public JpaExpression<Duration> durationDiff(Expression<Duration> x, Expression<Duration> y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<Duration>) x, (SqmExpression<Duration>) y );
}
@Override
public JpaExpression<Duration> durationDiff(Expression<Duration> x, Duration y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<Duration>) x, value( y ) );
}
@Override
public JpaExpression<Duration> durationScaled(Expression<? extends Number> number, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.MULTIPLY,
(SqmExpression<? extends Number>) number, (SqmExpression<Duration>) duration );
}
@Override
public JpaExpression<Duration> durationScaled(Number number, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.MULTIPLY,
value( number ), (SqmExpression<Duration>) duration );
}
@Override
public JpaExpression<Duration> durationScaled(Expression<? extends Number> number, Duration duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.MULTIPLY,
(SqmExpression<? extends Number>) number, value( duration ) );
}
@Override
public <T extends Temporal> JpaExpression<Duration> durationBetween(Expression<T> x, Expression<T> y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<T>) x, (SqmExpression<T>) y );
}
@Override
public <T extends Temporal> JpaExpression<Duration> durationBetween(Expression<T> x, T y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<T>) x, value( y ) );
}
@Override
public <T extends Temporal> JpaExpression<T> addDuration(Expression<T> datetime, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
(SqmExpression<T>) datetime, (SqmExpression<Duration>) duration );
}
@Override
public <T extends Temporal> JpaExpression<T> addDuration(Expression<T> datetime, Duration duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
(SqmExpression<T>) datetime, value( duration ) );
}
@Override
public <T extends Temporal> JpaExpression<T> addDuration(T datetime, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
value( datetime ), (SqmExpression<Duration>) duration );
}
@Override
public <T extends Temporal> JpaExpression<T> subtractDuration(Expression<T> datetime, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<T>) datetime, (SqmExpression<Duration>) duration );
}
@Override
public <T extends Temporal> JpaExpression<T> subtractDuration(Expression<T> datetime, Duration duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<T>) datetime, value( duration ) );
}
@Override
public <T extends Temporal> JpaExpression<T> subtractDuration(T datetime, Expression<Duration> duration) {
return createSqmArithmeticNode( BinaryArithmeticOperator.SUBTRACT,
value( datetime ), (SqmExpression<Duration>) duration );
}
@Override
public <N extends Number> SqmExpression<N> sum(Expression<? extends N> x, Expression<? extends N> y) {
return createSqmArithmeticNode( BinaryArithmeticOperator.ADD,
(SqmExpression<? extends N>) x, (SqmExpression<? extends N>) y );
}
private <N> SqmExpression<N> createSqmArithmeticNode(
BinaryArithmeticOperator operator,
SqmExpression<?> leftHandExpression,
SqmExpression<?> rightHandExpression) {
final SqmExpressible<?> arithmeticType =
getTypeConfiguration()
.resolveArithmeticType(
leftHandExpression.getNodeType(),
rightHandExpression.getNodeType(),
operator
);
@SuppressWarnings("unchecked")
final var castType = (SqmBindableType<N>) arithmeticType;
return new SqmBinaryArithmetic<>(
operator,
leftHandExpression,
rightHandExpression,
castType,
this
);
}
@Override
public <N extends Number> SqmExpression<N> sum(Expression<? extends N> x, N y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.ADD,
(SqmExpression<? extends N>) x,
value( y )
);
}
@Override
public <N extends Number> SqmExpression<N> sum(N x, Expression<? extends N> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.ADD,
value( x ),
(SqmExpression<? extends N>) y
);
}
@Override
public <N extends Number> SqmExpression<N> prod(Expression<? extends N> x, Expression<? extends N> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MULTIPLY,
(SqmExpression<? extends N>) x,
(SqmExpression<? extends N>) y
);
}
@Override
public <N extends Number> SqmExpression<N> prod(Expression<? extends N> x, N y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MULTIPLY,
(SqmExpression<? extends N>) x,
value( y )
);
}
@Override
public <N extends Number> SqmExpression<N> prod(N x, Expression<? extends N> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MULTIPLY,
value( x ),
(SqmExpression<? extends N>) y
);
}
@Override
public <N extends Number> SqmExpression<N> diff(Expression<? extends N> x, Expression<? extends N> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<? extends N>) x,
(SqmExpression<? extends N>) y
);
}
@Override
public <N extends Number> SqmExpression<N> diff(Expression<? extends N> x, N y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.SUBTRACT,
(SqmExpression<? extends N>) x,
value( y )
);
}
@Override
public <N extends Number> SqmExpression<N> diff(N x, Expression<? extends N> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.SUBTRACT,
value( x ),
(SqmExpression<? extends N>) y
);
}
@Override
public SqmExpression<Number> quot(Expression<? extends Number> x, Expression<? extends Number> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.QUOT,
(SqmExpression<? extends Number>) x,
(SqmExpression<? extends Number>) y
);
}
@Override
public SqmExpression<Number> quot(Expression<? extends Number> x, Number y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.QUOT,
(SqmExpression<? extends Number>) x,
value( y )
);
}
@Override
public SqmExpression<Number> quot(Number x, Expression<? extends Number> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.QUOT,
value( x ),
(SqmExpression<? extends Number>) y
);
}
@Override
public SqmExpression<Integer> mod(Expression<Integer> x, Expression<Integer> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MODULO,
(SqmExpression<Integer>) x,
(SqmExpression<Integer>) y
);
}
@Override
public SqmExpression<Integer> mod(Expression<Integer> x, Integer y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MODULO,
(SqmExpression<Integer>) x,
value( y )
);
}
@Override
public SqmExpression<Integer> mod(Integer x, Expression<Integer> y) {
return createSqmArithmeticNode(
BinaryArithmeticOperator.MODULO,
value( x ),
(SqmExpression<Integer>) y
);
}
@Override
public SqmExpression<Double> sqrt(Expression<? extends Number> x) {
return getFunctionDescriptor( "sqrt" ).generateSqmExpression(
(SqmTypedNode<?>) x,
null,
queryEngine
);
}
@Override
public SqmExpression<Long> toLong(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asLong();
}
@Override
public SqmExpression<Integer> toInteger(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asInteger();
}
@Override
public SqmExpression<Float> toFloat(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asFloat();
}
@Override
public SqmExpression<Double> toDouble(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asDouble();
}
@Override
public SqmExpression<BigDecimal> toBigDecimal(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asBigDecimal();
}
@Override
public SqmExpression<BigInteger> toBigInteger(Expression<? extends Number> number) {
return ( (SqmExpression<?>) number ).asBigInteger();
}
@Override
public SqmExpression<String> toString(Expression<Character> character) {
return ( (SqmExpression<?>) character ).asString();
}
public <T> SqmLiteral<T> literal(@Nullable T value, @Nullable SqmExpression<? extends T> typeInferenceSource) {
return value == null
? new SqmLiteralNull<>( this )
: createLiteral( value, resolveInferredType( value, typeInferenceSource ) );
}
private <T> SqmLiteral<T> createLiteral(T value, SqmBindableType<T> expressible) {
if ( expressible.getExpressibleJavaType().isInstance( value ) ) {
return new SqmLiteral<>( value, expressible, this );
}
else {
// Just like in HQL, we allow coercion of literal values to the inferred type
final T coercedValue =
expressible.getExpressibleJavaType()
.coerce( value, this::getTypeConfiguration );
// ignore typeInferenceSource and fallback the value type
return expressible.getExpressibleJavaType().isInstance( coercedValue )
? new SqmLiteral<>( coercedValue, expressible, this )
: literal( value );
}
}
private <T> SqmBindableType<? extends T> resolveInferredType(
@Nullable T value, @Nullable SqmExpression<? extends T> typeInferenceSource) {
if ( typeInferenceSource != null ) {
return typeInferenceSource.getNodeType();
}
else if ( value == null ) {
return null;
}
else {
return resolveInferredType( value );
}
}
private <T> BasicType<T> resolveInferredType(T value) {
final TypeConfiguration typeConfiguration = getTypeConfiguration();
final Class<T> type = ReflectHelper.getClass( value );
final BasicType<T> result = typeConfiguration.getBasicTypeForJavaType( type );
if ( result == null && value instanceof Enum<?> enumValue ) {
return (BasicType<T>) resolveEnumType( typeConfiguration, enumValue );
}
else {
return result;
}
}
private static <E extends Enum<E>> BasicType<E> resolveEnumType(TypeConfiguration configuration, Enum<E> enumValue) {
final EnumJavaType<E> javaType = new EnumJavaType<>( ReflectHelper.getClass( enumValue ) );
final JdbcType jdbcType = javaType.getRecommendedJdbcType( configuration.getCurrentBaseSqlTypeIndicators() );
return configuration.getBasicTypeRegistry().resolve( javaType, jdbcType );
}
@Override
public <T> SqmLiteral<T> literal(@Nullable T value) {
if ( value == null ) {
if ( jpaCompliance.isJpaQueryComplianceEnabled() ) {
throw new IllegalArgumentException( "literal value cannot be null" );
}
return new SqmLiteralNull<>( this );
}
else {
return new SqmLiteral<>( value, resolveExpressible( getParameterBindType( value ) ), this );
}
}
@Override
public MappingMetamodelImplementor getMappingMetamodel() {
return (MappingMetamodelImplementor) bindingContext.getMappingMetamodel();
}
@Override
public <T> List<? extends SqmExpression<T>> literals(T[] values) {
if ( values == null || values.length == 0 ) {
return Collections.emptyList();
}
final List<SqmLiteral<T>> literals = new ArrayList<>();
for ( T value : values ) {
literals.add( literal( value ) );
}
return literals;
}
@Override
public <T> List<? extends SqmExpression<T>> literals(List<T> values) {
if ( values == null || values.isEmpty() ) {
return Collections.emptyList();
}
final List<SqmLiteral<T>> literals = new ArrayList<>();
for ( T value : values ) {
literals.add( literal( value ) );
}
return literals;
}
@Override
public <T> SqmExpression<T> nullLiteral(Class<T> resultClass) {
if ( resultClass.isEnum() ) {
// No basic types are registered for
|
SqmCriteriaNodeBuilder
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/test/fakemetrics/ReceivedMessage.java
|
{
"start": 532,
"end": 1272
}
|
class ____ {
public final String address;
public final boolean publish;
public final boolean local;
public final int handlers;
public ReceivedMessage(String address, boolean publish, boolean local, int handlers) {
this.address = address;
this.publish = publish;
this.local = local;
this.handlers = handlers;
}
@Override
public boolean equals(Object obj) {
ReceivedMessage that = (ReceivedMessage) obj;
return address.equals(that.address) && publish == that.publish && local == that.local && handlers == that.handlers;
}
@Override
public String toString() {
return "Message[address" + address + ",publish=" + publish + ",local=" + local + ",handlers=" + handlers + "]";
}
}
|
ReceivedMessage
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/state/ChangelogTestUtils.java
|
{
"start": 4671,
"end": 6267
}
|
class ____ extends InMemoryChangelogStateHandle
implements TestStreamStateHandle {
private static final long serialVersionUID = 1L;
private volatile boolean isDiscarded;
public ChangelogStateHandleWrapper(InMemoryChangelogStateHandle stateHandle) {
super(
stateHandle.getChanges(),
SequenceNumber.of(stateHandle.getFrom()),
SequenceNumber.of(stateHandle.getTo()),
stateHandle.getKeyGroupRange());
}
@Override
public void registerSharedStates(SharedStateRegistry stateRegistry, long checkpointID) {
// unlike original InMemoryChangelogStateHandle, register the reference here
// to verify #isDiscarded
stateRegistry.registerReference(getSharedStateRegistryKey(), this, checkpointID);
}
private SharedStateRegistryKey getSharedStateRegistryKey() {
return new SharedStateRegistryKey(getKeyGroupRange() + "_" + getFrom() + "_" + getTo());
}
@Override
public void discardState() {
super.discardState();
isDiscarded = true;
}
@Override
public FSDataInputStream openInputStream() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Optional<byte[]> asBytesIfInMemory() {
throw new UnsupportedOperationException();
}
boolean isDiscarded() {
return isDiscarded;
}
}
}
|
ChangelogStateHandleWrapper
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/routebuilder/MyOtherRoute.java
|
{
"start": 942,
"end": 1443
}
|
class ____ extends RouteBuilder {
private CamelContext ctx;
@Override
public void configure() throws Exception {
from("direct:b").to("mock:b");
}
@Override
public void setCamelContext(CamelContext context) {
this.ctx = context;
if (!"foo".equals(context.getName())) {
throw new IllegalArgumentException("Should be named foo");
}
}
@Override
public CamelContext getCamelContext() {
return ctx;
}
}
|
MyOtherRoute
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EmbeddableWithDeclaredDataTest.java
|
{
"start": 955,
"end": 2482
}
|
class ____ {
private long id;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
this.id = scope.fromTransaction( entityManager -> {
EntityWithEmbeddableWithDeclaredData entity = new EntityWithEmbeddableWithDeclaredData();
entity.setName( "Entity 1" );
entity.setValue( new EmbeddableWithDeclaredData( 42, "TestCodeart" ) );
entityManager.persist( entity );
return entity.getId();
} );
}
@Test
@FailureExpected( jiraKey = "HHH-9193" )
public void testEmbeddableThatExtendsMappedSuperclass(EntityManagerFactoryScope scope) {
scope.inEntityManager( entityManager -> {
EntityWithEmbeddableWithDeclaredData entityLoaded = entityManager.find( EntityWithEmbeddableWithDeclaredData.class, id );
AuditReader reader = AuditReaderFactory.get( entityManager );
List<Number> revs = reader.getRevisions( EntityWithEmbeddableWithDeclaredData.class, id );
assertThat( revs ).hasSize( 1 );
EntityWithEmbeddableWithDeclaredData entityRev1 = reader.find( EntityWithEmbeddableWithDeclaredData.class, id, revs.get( 0 ) );
assertThat( entityRev1.getName() ).isEqualTo( entityLoaded.getName() );
// only value.codeArt should be audited because it is the only audited field in EmbeddableWithDeclaredData;
// fields in AbstractEmbeddable should not be audited.
assertThat( entityRev1.getValue().getCodeart() ).isEqualTo( entityLoaded.getValue().getCodeart() );
assertThat( entityRev1.getValue().getCode() ).isEqualTo( 0 );
} );
}
}
|
EmbeddableWithDeclaredDataTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/dataframe/RestPreviewDataFrameAnalyticsAction.java
|
{
"start": 1362,
"end": 4792
}
|
class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(
new Route(GET, BASE_PATH + "data_frame/analytics/_preview"),
new Route(POST, BASE_PATH + "data_frame/analytics/_preview"),
new Route(GET, BASE_PATH + "data_frame/analytics/{" + DataFrameAnalyticsConfig.ID + "}/_preview"),
new Route(POST, BASE_PATH + "data_frame/analytics/{" + DataFrameAnalyticsConfig.ID + "}/_preview")
);
}
@Override
public String getName() {
return "ml_preview_data_frame_analytics_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
final String jobId = restRequest.param(DataFrameAnalyticsConfig.ID.getPreferredName());
if (Strings.isNullOrEmpty(jobId) && restRequest.hasContentOrSourceParam() == false) {
throw ExceptionsHelper.badRequestException(
"Please provide a job [{}] or the config object",
DataFrameAnalyticsConfig.ID.getPreferredName()
);
}
if (Strings.isNullOrEmpty(jobId) == false && restRequest.hasContentOrSourceParam()) {
throw ExceptionsHelper.badRequestException(
"Please provide either a job [{}] or the config object but not both",
DataFrameAnalyticsConfig.ID.getPreferredName()
);
}
final PreviewDataFrameAnalyticsAction.Request.Builder requestBuilder = Strings.isNullOrEmpty(jobId)
? PreviewDataFrameAnalyticsAction.Request.fromXContent(restRequest.contentOrSourceParamParser())
: new PreviewDataFrameAnalyticsAction.Request.Builder();
return channel -> {
RestToXContentListener<PreviewDataFrameAnalyticsAction.Response> listener = new RestToXContentListener<>(channel);
RestCancellableNodeClient cancellableClient = new RestCancellableNodeClient(client, restRequest.getHttpChannel());
if (requestBuilder.getConfig() != null) {
cancellableClient.execute(PreviewDataFrameAnalyticsAction.INSTANCE, requestBuilder.build(), listener);
} else {
GetDataFrameAnalyticsAction.Request getRequest = new GetDataFrameAnalyticsAction.Request(jobId);
getRequest.setAllowNoResources(false);
cancellableClient.execute(GetDataFrameAnalyticsAction.INSTANCE, getRequest, ActionListener.wrap(getResponse -> {
List<DataFrameAnalyticsConfig> jobs = getResponse.getResources().results();
if (jobs.size() > 1) {
listener.onFailure(
ExceptionsHelper.badRequestException(
"expected only one config but matched {}",
jobs.stream().map(DataFrameAnalyticsConfig::getId).collect(Collectors.toList())
)
);
} else {
cancellableClient.execute(
PreviewDataFrameAnalyticsAction.INSTANCE,
requestBuilder.setConfig(jobs.get(0)).build(),
listener
);
}
}, listener::onFailure));
}
};
}
}
|
RestPreviewDataFrameAnalyticsAction
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/tool/schema/spi/GeneratorSynchronizer.java
|
{
"start": 334,
"end": 910
}
|
interface ____ {
/**
* Perform sequence resynchronization from the indicated source(s) to the indicated target(s).
* @param metadata Represents the schema to be dropped.
* @param options Options for executing the drop
* @param contributableInclusionFilter Filter for Contributable instances to use
* @param targetDescriptor description of the target(s) for the drop commands
*/
void doSynchronize(
Metadata metadata,
ExecutionOptions options,
ContributableMatcher contributableInclusionFilter,
TargetDescriptor targetDescriptor);
}
|
GeneratorSynchronizer
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java
|
{
"start": 2093,
"end": 2556
}
|
class ____ {
public void test() {
used();
}
private void used() {}
// BUG: Diagnostic contains: Method 'notUsed' is never used.
private void notUsed() {}
@Inject
private void notUsedExempted() {}
@Keep
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
private @
|
UnusedPrivateMethod
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/clientproxy/bridgemethod/SameDescriptorDifferentReturnTypeMethodTest.java
|
{
"start": 1824,
"end": 1888
}
|
interface ____ {
Serializable next();
}
|
SuperLoop
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/booleanarrays/BooleanArrays_assertContainsExactly_Test.java
|
{
"start": 1876,
"end": 5154
}
|
class ____ extends BooleanArraysBaseTest {
@Test
void should_pass_if_actual_contains_given_values_exactly() {
arrays.assertContainsExactly(someInfo(), actual, arrayOf(true, false));
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
arrays.assertContainsExactly(someInfo(), emptyArray(), emptyArray());
}
@Test
void should_fail_if_actual_contains_given_values_exactly_but_in_different_order() {
AssertionInfo info = someInfo();
boolean[] expected = arrayOf(false, true);
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, elementsDifferAtIndex(true, false, 0), asList(actual), asList(expected));
}
@Test
void should_fail_if_arrays_have_different_sizes() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), actual,
arrayOf(true)));
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), actual,
emptyArray()));
}
@Test
void should_throw_error_if_array_of_values_to_look_for_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertContainsExactly(someInfo(),
actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), null,
arrayOf(true)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_does_not_contain_given_values_exactly() {
AssertionInfo info = someInfo();
boolean[] expected = { true, true };
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info,
shouldContainExactly(actual, asList(expected), newArrayList(true), newArrayList(false)),
asList(actual), asList(expected));
}
@Test
void should_fail_if_actual_contains_all_given_values_but_size_differ() {
AssertionInfo info = someInfo();
boolean[] actual = { true, true };
boolean[] expected = { true };
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info,
shouldContainExactly(actual, asList(expected), newArrayList(), newArrayList(true)), asList(actual),
asList(expected));
}
}
|
BooleanArrays_assertContainsExactly_Test
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/http2/Http2RSTFloodProtectionConfigTest.java
|
{
"start": 1427,
"end": 4233
}
|
class ____ {
private static final String configuration = """
quarkus.http.ssl.certificate.key-store-file=server-keystore.jks
quarkus.http.ssl.certificate.key-store-password=secret
quarkus.http.limits.rst-flood-max-rst-frame-per-window=10
quarkus.http.limits.rst-flood-window-duration=10s
""";
@TestHTTPResource(value = "/ping", ssl = true)
URL sslUrl;
@TestHTTPResource(value = "/ping")
URL url;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyBean.class)
.addAsResource(new StringAsset(configuration), "application.properties")
.addAsResource(new File("target/certs/ssl-test-keystore.jks"), "server-keystore.jks"));
@Test
void testRstFloodProtectionWithTlsEnabled() throws Exception {
HttpClientOptions options = new HttpClientOptions()
.setUseAlpn(true)
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setTrustOptions(new JksOptions().setPath(new File("target/certs/ssl-test-truststore.jks").getAbsolutePath())
.setPassword("secret"));
var client = VertxCoreRecorder.getVertx().get().createHttpClient(options);
int port = sslUrl.getPort();
run(client, port, false);
}
@Test
public void testRstFloodProtection() throws InterruptedException {
HttpClientOptions options = new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(true);
var client = VertxCoreRecorder.getVertx().get().createHttpClient(options);
run(client, url.getPort(), true);
}
void run(HttpClient client, int port, boolean plain) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
client.connectionHandler(conn -> conn.goAwayHandler(ga -> {
Assertions.assertEquals(11, ga.getErrorCode());
latch.countDown();
}));
if (plain) {
// Emit a first request to establish a connection.
// It's HTTP/1 so, does not count in the number of requests.
client.request(GET, port, "localhost", "/ping")
.compose(HttpClientRequest::send);
}
for (int i = 0; i < 20; i++) {
client.request(GET, port, "localhost", "/ping")
.onSuccess(req -> req.end().onComplete(v -> req.reset()));
}
if (!latch.await(10, TimeUnit.SECONDS)) {
fail("RST flood protection failed");
}
}
@ApplicationScoped
public static
|
Http2RSTFloodProtectionConfigTest
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringCustomExpressionTest.java
|
{
"start": 1123,
"end": 1750
}
|
class ____ extends SpringTestSupport {
@Test
public void testTransformMyExpression() throws InterruptedException {
getMockEndpoint("mock:result").expectedBodiesReceived("Yes Camel rocks", "Hello World");
template.sendBody("direct:start", "Camel");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/processor/SpringCustomExpressionTest.xml");
}
public static
|
SpringCustomExpressionTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/IntegerAssert.java
|
{
"start": 1110,
"end": 1365
}
|
class ____ extends AbstractIntegerAssert<IntegerAssert> {
public IntegerAssert(Integer actual) {
super(actual, IntegerAssert.class);
}
public IntegerAssert(AtomicInteger actual) {
this(actual == null ? null : actual.get());
}
}
|
IntegerAssert
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpqlQueryBuilder.java
|
{
"start": 1637,
"end": 10657
}
|
class ____ {
private JpqlQueryBuilder() {}
/**
* Create an {@link Entity} from the given {@link JpaEntityMetadata}.
*
* @param from the entity type to select from.
* @return
*/
public static Entity entity(JpaEntityMetadata<?> from) {
return new Entity(from.getJavaType(), from.getEntityName(),
getAlias(from.getJavaType().getSimpleName(), Predicates.isTrue(), () -> "r"));
}
/**
* Create a {@link Join INNER JOIN}.
*
* @param origin the selection origin (a join or the entity itself) to select from.
* @param path
* @return
*/
public static Join innerJoin(Origin origin, String path) {
return new Join(origin, "INNER JOIN", path);
}
/**
* Create a {@link Join LEFT JOIN}.
*
* @param origin the selection origin (a join or the entity itself) to select from.
* @param path
* @return
*/
public static Join leftJoin(Origin origin, String path) {
return new Join(origin, "LEFT JOIN", path);
}
/**
* Start building a {@link Select} statement by selecting {@link Entity from}.
*
* @param from the entity source to select from.
* @return a new select builder.
*/
public static SelectStep selectFrom(Entity from) {
return new SelectStep() {
boolean distinct = false;
@Override
public SelectStep distinct() {
distinct = true;
return this;
}
@Override
public Select entity() {
return new Select(postProcess(new EntitySelection(from)), from);
}
@Override
public Select count() {
return new Select(new CountSelection(from, distinct), from);
}
@Override
public Select instantiate(String resultType, Collection<? extends JpqlQueryBuilder.Expression> paths) {
return new Select(postProcess(new ConstructorExpression(resultType, new Multiselect(from, paths))), from);
}
@Override
public Select select(Collection<? extends JpqlQueryBuilder.Expression> paths) {
return new Select(postProcess(new Multiselect(from, paths)), from);
}
@Override
public Select select(Selection selection) {
return new Select(postProcess(selection), from);
}
Selection postProcess(Selection selection) {
return distinct ? new DistinctSelection(selection) : selection;
}
};
}
private static String getAlias(String from, java.util.function.Predicate<String> predicate,
Supplier<String> fallback) {
StringBuilder builder = new StringBuilder();
char[] charArray = from.toLowerCase(Locale.ROOT).toCharArray();
for (char c : charArray) {
if (Character.isJavaIdentifierPart(c)) {
builder.append(c);
} else {
break;
}
}
if (builder.isEmpty()) {
return fallback.get();
}
String identifier = builder.toString();
String firstChar = identifier.substring(0, 1);
if (predicate.test(firstChar)) {
return firstChar;
}
for (int i = 0; i < 10; i++) {
String candidate = firstChar + "_" + i;
if (predicate.test(candidate)) {
return candidate;
}
}
return fallback.get();
}
/**
* Invoke a {@literal function} with the given {@code arguments}.
*
* @param function function name.
* @param arguments function arguments.
* @return an expression representing a function call.
*/
public static Expression function(String function, Expression... arguments) {
return new FunctionExpression(function, Arrays.asList(arguments));
}
/**
* Nest the given {@link Predicate}.
*
* @param predicate
* @return
*/
public static Predicate nested(Predicate predicate) {
return new NestedPredicate(predicate);
}
/**
* Create a qualified expression for a {@link PropertyPath}.
*
* @param source
* @param path
* @return
*/
public static Expression expression(Origin source, PropertyPath path) {
return new PathAndOrigin(path, source, false);
}
/**
* Create a simple expression from a string as-is.
*
* @param expression
* @return
*/
public static Expression expression(String expression) {
Assert.hasText(expression, "Expression must not be empty or null");
return new LiteralExpression(expression);
}
/**
* Create a simple numeric literal.
*
* @param literal
* @return
*/
public static Expression literal(Number literal) {
return new LiteralExpression(literal.toString());
}
/**
* Create a simple literal from a string by quoting it.
*
* @param literal
* @return
*/
public static Expression literal(String literal) {
return new StringLiteralExpression(literal);
}
/**
* A parameter placeholder.
*
* @param parameter
* @return
*/
public static Expression parameter(String parameter) {
Assert.hasText(parameter, "Parameter must not be empty or null");
return new ParameterExpression(new ParameterPlaceholder(parameter));
}
/**
* A parameter placeholder.
*
* @param placeholder the placeholder to use.
* @return
*/
public static Expression parameter(ParameterPlaceholder placeholder) {
return new ParameterExpression(placeholder);
}
/**
* Create a new ordering expression.
*
* @param sortExpression
* @return
* @since 4.0
*/
public static Expression orderBy(Expression sortExpression) {
return new OrderExpression(sortExpression, null, Sort.NullHandling.NATIVE);
}
/**
* Create a new ordering expression.
*
* @param sortExpression
* @param order
* @return
*/
public static Expression orderBy(Expression sortExpression, Sort.Order order) {
return new OrderExpression(sortExpression, order.getDirection(), order.getNullHandling());
}
/**
* Create a new ordering expression.
*
* @param sortExpression
* @param direction
* @return
* @since 4.0
*/
public static Expression orderBy(Expression sortExpression, Sort.Direction direction) {
return new OrderExpression(sortExpression, direction, Sort.NullHandling.NATIVE);
}
/**
* Start building a {@link Predicate WHERE predicate} by providing the right-hand side.
*
* @param source
* @param path
* @return
*/
public static WhereStep where(Origin source, PropertyPath path) {
return where(expression(source, path));
}
/**
* Start building a {@link Predicate WHERE predicate} by providing the right-hand side.
*
* @param rhs
* @return
*/
public static WhereStep where(Expression rhs) {
return new WhereStep() {
@Override
public Predicate between(Expression lower, Expression upper) {
return new BetweenPredicate(rhs, lower, upper);
}
@Override
public Predicate gt(Expression value) {
return new OperatorPredicate(rhs, ">", value);
}
@Override
public Predicate gte(Expression value) {
return new OperatorPredicate(rhs, ">=", value);
}
@Override
public Predicate lt(Expression value) {
return new OperatorPredicate(rhs, "<", value);
}
@Override
public Predicate lte(Expression value) {
return new OperatorPredicate(rhs, "<=", value);
}
@Override
public Predicate isNull() {
return new LhsPredicate(rhs, "IS NULL");
}
@Override
public Predicate isNotNull() {
return new LhsPredicate(rhs, "IS NOT NULL");
}
@Override
public Predicate isTrue() {
return new LhsPredicate(rhs, "= TRUE");
}
@Override
public Predicate isFalse() {
return new LhsPredicate(rhs, "= FALSE");
}
@Override
public Predicate isEmpty() {
return new LhsPredicate(rhs, "IS EMPTY");
}
@Override
public Predicate isNotEmpty() {
return new LhsPredicate(rhs, "IS NOT EMPTY");
}
@Override
public Predicate in(Expression value) {
return new InPredicate(rhs, "IN", value);
}
@Override
public Predicate notIn(Expression value) {
return new InPredicate(rhs, "NOT IN", value);
}
@Override
public Predicate memberOf(Expression value) {
return new MemberOfPredicate(rhs, "MEMBER OF", value);
}
@Override
public Predicate notMemberOf(Expression value) {
return new MemberOfPredicate(rhs, "NOT MEMBER OF", value);
}
@Override
public Predicate like(Expression value, String escape) {
return new LikePredicate(rhs, "LIKE", value, escape);
}
@Override
public Predicate notLike(Expression value, String escape) {
return new LikePredicate(rhs, "NOT LIKE", value, escape);
}
@Override
public Predicate eq(Expression value) {
return new OperatorPredicate(rhs, "=", value);
}
@Override
public Predicate neq(Expression value) {
return new OperatorPredicate(rhs, "!=", value);
}
};
}
public static @Nullable Predicate and(List<Predicate> intermediate) {
Predicate predicate = null;
for (Predicate other : intermediate) {
if (predicate == null) {
predicate = other;
} else {
predicate = predicate.and(other);
}
}
return predicate;
}
public static @Nullable Predicate or(List<Predicate> intermediate) {
Predicate predicate = null;
for (Predicate other : intermediate) {
if (predicate == null) {
predicate = other;
} else {
predicate = predicate.or(other);
}
}
return predicate;
}
/**
* Fluent
|
JpqlQueryBuilder
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableAnyTest.java
|
{
"start": 1243,
"end": 18715
}
|
class ____ extends RxJavaTest {
@Test
public void anyWithTwoItemsObservable() {
Observable<Integer> w = Observable.just(1, 2);
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(false);
verify(observer, times(1)).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void isEmptyWithTwoItemsObservable() {
Observable<Integer> w = Observable.just(1, 2);
Observable<Boolean> observable = w.isEmpty().toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(true);
verify(observer, times(1)).onNext(false);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void anyWithOneItemObservable() {
Observable<Integer> w = Observable.just(1);
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(false);
verify(observer, times(1)).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void isEmptyWithOneItemObservable() {
Observable<Integer> w = Observable.just(1);
Observable<Boolean> observable = w.isEmpty().toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(true);
verify(observer, times(1)).onNext(false);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void anyWithEmptyObservable() {
Observable<Integer> w = Observable.empty();
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, times(1)).onNext(false);
verify(observer, never()).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void isEmptyWithEmptyObservable() {
Observable<Integer> w = Observable.empty();
Observable<Boolean> observable = w.isEmpty().toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, times(1)).onNext(true);
verify(observer, never()).onNext(false);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void anyWithPredicate1Observable() {
Observable<Integer> w = Observable.just(1, 2, 3);
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 2;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(false);
verify(observer, times(1)).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void exists1Observable() {
Observable<Integer> w = Observable.just(1, 2, 3);
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 2;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, never()).onNext(false);
verify(observer, times(1)).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void anyWithPredicate2Observable() {
Observable<Integer> w = Observable.just(1, 2, 3);
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 1;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, times(1)).onNext(false);
verify(observer, never()).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void anyWithEmptyAndPredicateObservable() {
// If the source is empty, always output false.
Observable<Integer> w = Observable.empty();
Observable<Boolean> observable = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return true;
}
}).toObservable();
Observer<Boolean> observer = TestHelper.mockObserver();
observable.subscribe(observer);
verify(observer, times(1)).onNext(false);
verify(observer, never()).onNext(true);
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void withFollowingFirstObservable() {
Observable<Integer> o = Observable.fromArray(1, 3, 5, 6);
Observable<Boolean> anyEven = o.any(new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i % 2 == 0;
}
}).toObservable();
assertTrue(anyEven.blockingFirst());
}
@Test
public void issue1935NoUnsubscribeDownstreamObservable() {
Observable<Integer> source = Observable.just(1).isEmpty().toObservable()
.flatMap(new Function<Boolean, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Boolean t1) {
return Observable.just(2).delay(500, TimeUnit.MILLISECONDS);
}
});
assertEquals((Object)2, source.blockingFirst());
}
@Test
public void predicateThrowsExceptionAndValueInCauseMessageObservable() {
TestObserverEx<Boolean> to = new TestObserverEx<>();
final IllegalArgumentException ex = new IllegalArgumentException();
Observable.just("Boo!").any(new Predicate<String>() {
@Override
public boolean test(String v) {
throw ex;
}
}).subscribe(to);
to.assertTerminated();
to.assertNoValues();
to.assertNotComplete();
to.assertError(ex);
// FIXME value as last cause?
// assertTrue(ex.getCause().getMessage().contains("Boo!"));
}
@Test
public void anyWithTwoItems() {
Observable<Integer> w = Observable.just(1, 2);
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(false);
verify(observer, times(1)).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void isEmptyWithTwoItems() {
Observable<Integer> w = Observable.just(1, 2);
Single<Boolean> single = w.isEmpty();
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(true);
verify(observer, times(1)).onSuccess(false);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void anyWithOneItem() {
Observable<Integer> w = Observable.just(1);
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(false);
verify(observer, times(1)).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void isEmptyWithOneItem() {
Observable<Integer> w = Observable.just(1);
Single<Boolean> single = w.isEmpty();
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(true);
verify(observer, times(1)).onSuccess(false);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void anyWithEmpty() {
Observable<Integer> w = Observable.empty();
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) {
return true;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, times(1)).onSuccess(false);
verify(observer, never()).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void isEmptyWithEmpty() {
Observable<Integer> w = Observable.empty();
Single<Boolean> single = w.isEmpty();
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, times(1)).onSuccess(true);
verify(observer, never()).onSuccess(false);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void anyWithPredicate1() {
Observable<Integer> w = Observable.just(1, 2, 3);
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 2;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(false);
verify(observer, times(1)).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void exists1() {
Observable<Integer> w = Observable.just(1, 2, 3);
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 2;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, never()).onSuccess(false);
verify(observer, times(1)).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void anyWithPredicate2() {
Observable<Integer> w = Observable.just(1, 2, 3);
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t1) {
return t1 < 1;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, times(1)).onSuccess(false);
verify(observer, never()).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void anyWithEmptyAndPredicate() {
// If the source is empty, always output false.
Observable<Integer> w = Observable.empty();
Single<Boolean> single = w.any(new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return true;
}
});
SingleObserver<Boolean> observer = TestHelper.mockSingleObserver();
single.subscribe(observer);
verify(observer, times(1)).onSuccess(false);
verify(observer, never()).onSuccess(true);
verify(observer, never()).onError(any(Throwable.class));
}
@Test
public void withFollowingFirst() {
Observable<Integer> o = Observable.fromArray(1, 3, 5, 6);
Single<Boolean> anyEven = o.any(new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i % 2 == 0;
}
});
assertTrue(anyEven.blockingGet());
}
@Test
public void issue1935NoUnsubscribeDownstream() {
Observable<Integer> source = Observable.just(1).isEmpty()
.flatMapObservable(new Function<Boolean, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Boolean t1) {
return Observable.just(2).delay(500, TimeUnit.MILLISECONDS);
}
});
assertEquals((Object)2, source.blockingFirst());
}
@Test
public void predicateThrowsExceptionAndValueInCauseMessage() {
TestObserverEx<Boolean> to = new TestObserverEx<>();
final IllegalArgumentException ex = new IllegalArgumentException();
Observable.just("Boo!").any(new Predicate<String>() {
@Override
public boolean test(String v) {
throw ex;
}
}).subscribe(to);
to.assertTerminated();
to.assertNoValues();
to.assertNotComplete();
to.assertError(ex);
// FIXME value as last cause?
// assertTrue(ex.getCause().getMessage().contains("Boo!"));
}
@Test
public void dispose() {
TestHelper.checkDisposed(Observable.just(1).any(Functions.alwaysTrue()).toObservable());
TestHelper.checkDisposed(Observable.just(1).any(Functions.alwaysTrue()));
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Observable<Object> o) throws Exception {
return o.any(Functions.alwaysTrue()).toObservable();
}
});
TestHelper.checkDoubleOnSubscribeObservableToSingle(new Function<Observable<Object>, SingleSource<Boolean>>() {
@Override
public SingleSource<Boolean> apply(Observable<Object> o) throws Exception {
return o.any(Functions.alwaysTrue());
}
});
}
@Test
public void predicateThrowsSuppressOthers() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
new Observable<Integer>() {
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
observer.onNext(1);
observer.onNext(2);
observer.onError(new IOException());
observer.onComplete();
}
}
.any(new Predicate<Integer>() {
@Override
public boolean test(Integer v) throws Exception {
throw new TestException();
}
})
.toObservable()
.test()
.assertFailure(TestException.class);
TestHelper.assertUndeliverable(errors, 0, IOException.class);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void badSourceSingle() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
new Observable<Integer>() {
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
observer.onError(new TestException("First"));
observer.onNext(1);
observer.onError(new TestException("Second"));
observer.onComplete();
}
}
.any(Functions.alwaysTrue())
.to(TestHelper.<Boolean>testConsumer())
.assertFailureAndMessage(TestException.class, "First");
TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
} finally {
RxJavaPlugins.reset();
}
}
}
|
ObservableAnyTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/filter/RestUpdateFilterAction.java
|
{
"start": 1063,
"end": 1880
}
|
class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, BASE_PATH + "filters/{" + ID + "}/_update"));
}
@Override
public String getName() {
return "ml_update_filter_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
String filterId = restRequest.param(MlFilter.ID.getPreferredName());
XContentParser parser = restRequest.contentOrSourceParamParser();
UpdateFilterAction.Request putFilterRequest = UpdateFilterAction.Request.parseRequest(filterId, parser);
return channel -> client.execute(UpdateFilterAction.INSTANCE, putFilterRequest, new RestToXContentListener<>(channel));
}
}
|
RestUpdateFilterAction
|
java
|
junit-team__junit5
|
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsWithGenericTypeHierarchiesTests.java
|
{
"start": 956,
"end": 1314
}
|
class ____ implements InterfaceGenericNumber<Number>, InterfaceDouble {
}
var methodAB = findMethod(AB.class, "foo", Double.class).orElseThrow();
var methodBA = findMethod(BA.class, "foo", Double.class).orElseThrow();
assertEquals(methodAB, methodBA);
}
@Test
void findMoreSpecificMethodFromAbstractImplementationOverDefaultInterfaceMethod() {
|
BA
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/AbstractAssociationCollectionEventTest.java
|
{
"start": 851,
"end": 2602
}
|
class ____ extends AbstractCollectionEventTest {
@Test
@SkipForDialect(dialectClass = HANADialect.class,
reason = " HANA doesn't support tables consisting of only a single auto-generated column")
public void testDeleteParentButNotChild(SessionFactoryScope scope) {
CollectionListeners listeners = new CollectionListeners( scope.getSessionFactory() );
ParentWithCollection parent = createParentWithOneChild( "parent", "child", scope );
ChildEntity child = (ChildEntity) parent.getChildren().iterator().next();
listeners.clear();
Session s = scope.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
parent = (ParentWithCollection) s.get( parent.getClass(), parent.getId() );
child = (ChildEntity) s.get( child.getClass(), child.getId() );
parent.removeChild( child );
s.remove( parent );
tx.commit();
s.close();
int index = 0;
checkResult( listeners, listeners.getInitializeCollectionListener(), parent, index++ );
if ( child instanceof ChildWithBidirectionalManyToMany ) {
checkResult( listeners, listeners.getInitializeCollectionListener(),
(ChildWithBidirectionalManyToMany) child, index++ );
}
checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, index++ );
checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, index++ );
if ( child instanceof ChildWithBidirectionalManyToMany ) {
checkResult( listeners, listeners.getPreCollectionUpdateListener(),
(ChildWithBidirectionalManyToMany) child, index++ );
checkResult( listeners, listeners.getPostCollectionUpdateListener(),
(ChildWithBidirectionalManyToMany) child, index++ );
}
checkNumberOfResults( listeners, index );
}
}
|
AbstractAssociationCollectionEventTest
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/OrderedMethodTests.java
|
{
"start": 21487,
"end": 21769
}
|
class ____ {
@BeforeEach
void trackInvocations(TestInfo testInfo) {
callSequence.add(testInfo.getDisplayName());
}
@Test
void test1() {
}
@Test
void test4() {
}
@Test
void test2() {
}
@Test
void test3() {
}
}
static
|
MisbehavingByRemovingTestCase
|
java
|
spring-projects__spring-security
|
web/src/test/java/org/springframework/security/web/server/authentication/HttpStatusServerEntryPointTests.java
|
{
"start": 1207,
"end": 2144
}
|
class ____ {
private MockServerHttpRequest request;
private MockServerWebExchange exchange;
private AuthenticationException authException;
private HttpStatusServerEntryPoint entryPoint;
@BeforeEach
public void setup() {
this.request = MockServerHttpRequest.get("/").build();
this.exchange = MockServerWebExchange.from(this.request);
this.authException = new AuthenticationException("") {
};
this.entryPoint = new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED);
}
@Test
public void constructorNullStatus() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new HttpStatusServerEntryPoint(null))
.withMessage("httpStatus cannot be null");
}
@Test
public void unauthorized() {
this.entryPoint.commence(this.exchange, this.authException).block();
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
}
|
HttpStatusServerEntryPointTests
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/RethrowReflectiveOperationExceptionAsLinkageError.java
|
{
"start": 1860,
"end": 3659
}
|
class ____ extends BugChecker
implements ThrowTreeMatcher {
private static final String ASSERTION_ERROR = "java.lang.AssertionError";
private static final String REFLECTIVE_OPERATION_EXCEPTION =
"java.lang.ReflectiveOperationException";
private static final Matcher<ExpressionTree> MATCHER = constructor().forClass(ASSERTION_ERROR);
@Override
public Description matchThrow(ThrowTree throwTree, VisitorState state) {
if (!MATCHER.matches(throwTree.getExpression(), state)) {
return NO_MATCH;
}
NewClassTree newClassTree = (NewClassTree) throwTree.getExpression();
List<? extends ExpressionTree> arguments = newClassTree.getArguments();
if (arguments.isEmpty() || arguments.size() > 2) {
return NO_MATCH;
}
Symbol cause = ASTHelpers.getSymbol(Iterables.getLast(arguments));
if (cause == null || !isReflectiveOperationException(state, cause)) {
return NO_MATCH;
}
String message =
arguments.size() == 1
? String.format("%s.getMessage()", cause.getSimpleName())
: state.getSourceForNode(arguments.getFirst());
return describeMatch(
newClassTree,
SuggestedFix.replace(
newClassTree,
String.format("new LinkageError(%s, %s)", message, cause.getSimpleName())));
}
private static boolean isReflectiveOperationException(VisitorState state, Symbol symbol) {
return isSameType(symbol.asType(), JAVA_LANG_REFLECTIVEOPERATIONEXCEPTION.get(state), state)
&& symbol.getKind().equals(ElementKind.EXCEPTION_PARAMETER);
}
private static final Supplier<Type> JAVA_LANG_REFLECTIVEOPERATIONEXCEPTION =
VisitorState.memoize(state -> state.getTypeFromString(REFLECTIVE_OPERATION_EXCEPTION));
}
|
RethrowReflectiveOperationExceptionAsLinkageError
|
java
|
quarkusio__quarkus
|
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/HealthCheckOnManagementInterfaceTest.java
|
{
"start": 596,
"end": 1578
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyCheck.class))
.overrideConfigKey("quarkus.management.enabled", "true");
@Test
void testHealth() {
try {
RestAssured.defaultParser = Parser.JSON;
when().get("http://localhost:9001/q/health/live").then()
.body("status", is("UP"),
"checks.status", contains("UP"),
"checks.name", contains("my-check"));
when().get("http://localhost:9001/q/health/live").then()
.body("status", is("DOWN"),
"checks.status", contains("DOWN"),
"checks.name", contains("my-check"));
} finally {
RestAssured.reset();
}
}
@Liveness
static
|
HealthCheckOnManagementInterfaceTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.