proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/web/controller/SeedStarterMngController.java
|
SeedStarterMngController
|
saveSeedstarter
|
class SeedStarterMngController {
@Autowired
private VarietyService varietyService;
@Autowired
private SeedStarterService seedStarterService;
public SeedStarterMngController() {
super();
}
@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public List<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public List<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}
@RequestMapping({"/","/seedstartermng"})
public String showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"save"})
public String saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>}
@RequestMapping(value="/seedstartermng", params={"addRow"})
public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"removeRow"})
public String removeRow(final SeedStarter seedStarter, final BindingResult bindingResult, final HttpServletRequest req) {
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
seedStarter.getRows().remove(rowId.intValue());
return "seedstartermng";
}
}
|
if (bindingResult.hasErrors()) {
return "seedstartermng";
}
this.seedStarterService.add(seedStarter);
model.clear();
return "redirect:/seedstartermng";
| 568
| 59
| 627
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/web/conversion/DateFormatter.java
|
DateFormatter
|
createDateFormat
|
class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>}
}
|
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
| 170
| 57
| 227
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-thvsjsp/src/main/java/org/thymeleaf/examples/spring6/thvsjsp/SpringWebApplicationInitializer.java
|
SpringWebApplicationInitializer
|
getServletFilters
|
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public static final String CHARACTER_ENCODING = "UTF-8";
public SpringWebApplicationInitializer() {
super();
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { SpringWebConfig.class };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[0];
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>}
}
|
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding(CHARACTER_ENCODING);
encodingFilter.setForceEncoding(true);
return new Filter[] { encodingFilter };
| 190
| 55
| 245
|
<methods>public void <init>() <variables>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-thvsjsp/src/main/java/org/thymeleaf/examples/spring6/thvsjsp/business/entities/Subscription.java
|
Subscription
|
toString
|
class Subscription {
private String email;
private SubscriptionType subscriptionType = SubscriptionType.ALL_EMAILS;
public Subscription() {
super();
}
public String getEmail() {
return this.email;
}
public void setEmail(final String email) {
this.email = email;
}
public SubscriptionType getSubscriptionType() {
return this.subscriptionType;
}
public void setSubscriptionType(final SubscriptionType subscriptionType) {
this.subscriptionType = subscriptionType;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Subscription [email=" + this.email + ", subscriptionType="
+ this.subscriptionType + "]";
| 186
| 35
| 221
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-thvsjsp/src/main/java/org/thymeleaf/examples/spring6/thvsjsp/web/SpringWebConfig.java
|
SpringWebConfig
|
templateResolver
|
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
public SpringWebConfig() {
super();
}
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/*
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setBasename("Messages");
return resourceBundleMessageSource;
}
/* **************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS */
/* TemplateResolver <- TemplateEngine <- ViewResolver */
/* **************************************************************** */
@Bean
public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setContentType("text/html;encoding=utf-8");
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setViewNames(new String[] {"index","*th"});
viewResolver.setOrder(Integer.valueOf(1));
return viewResolver;
}
/* **************************************************************** */
/* JSP-SPECIFIC ARTIFACTS */
/* **************************************************************** */
@Bean
public InternalResourceViewResolver jspViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/templates/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewNames(new String[] {"*jsp"});
viewResolver.setOrder(Integer.valueOf(2));
return viewResolver;
}
/* ******************************************************************* */
/* Defines callback methods to customize the Java-based configuration */
/* for Spring MVC enabled via {@code @EnableWebMvc} */
/* ******************************************************************* */
/*
* Dispatcher configuration for serving static resources
*/
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
|
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
| 760
| 120
| 880
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-thvsjsp/src/main/java/org/thymeleaf/examples/spring6/thvsjsp/web/controller/SubscribeJsp.java
|
SubscribeJsp
|
subscribe
|
class SubscribeJsp {
private static final Logger log = LoggerFactory.getLogger(SubscribeJsp.class);
public SubscribeJsp() {
super();
}
@ModelAttribute("allTypes")
public SubscriptionType[] populateTypes() {
return new SubscriptionType[] { SubscriptionType.ALL_EMAILS, SubscriptionType.DAILY_DIGEST };
}
@RequestMapping({"/subscribejsp"})
public String showSubscription(final Subscription subscription) {
return "subscribejsp";
}
@RequestMapping(value="/subscribejsp", params={"save"})
public String subscribe(final Subscription subscription, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>}
}
|
if (bindingResult.hasErrors()) {
return "subscribejsp";
}
log.info("JUST ADDED SUBSCRIPTION: " + subscription);
model.clear();
return "redirect:/subscribejsp";
| 220
| 61
| 281
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/spring6/thymeleaf-examples-spring6-thvsjsp/src/main/java/org/thymeleaf/examples/spring6/thvsjsp/web/controller/SubscribeTh.java
|
SubscribeTh
|
subscribe
|
class SubscribeTh {
private static final Logger log = LoggerFactory.getLogger(SubscribeTh.class);
public SubscribeTh() {
super();
}
@ModelAttribute("allTypes")
public SubscriptionType[] populateTypes() {
return new SubscriptionType[] { SubscriptionType.ALL_EMAILS, SubscriptionType.DAILY_DIGEST };
}
@RequestMapping({"/subscribeth"})
public String showSubscription(final Subscription subscription) {
return "subscribeth";
}
@RequestMapping(value="/subscribeth", params={"save"})
public String subscribe(final Subscription subscription, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>}
}
|
if (bindingResult.hasErrors()) {
return "subscribeth";
}
log.info("JUST ADDED SUBSCRIPTION: " + subscription);
model.clear();
return "redirect:/subscribeth";
| 220
| 63
| 283
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot2/biglist/mvc/BigListMvcAppConfig.java
|
BigListMvcAppConfig
|
dataSource
|
class BigListMvcAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(BigListMvcAppConfig.class);
private ApplicationContext applicationContext;
public BigListMvcAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 134
| 153
| 287
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot2/biglist/mvc/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
hasNext
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Iterator<PlaylistEntry> findAllPlaylistEntries() {
return this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
}).iterator();
}
public Iterator<PlaylistEntry> findLargeCollectionPlaylistEntries() {
final List<PlaylistEntry> baseList =
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
});
return new Iterator<PlaylistEntry>() {
private static final int REPEATS = 300;
private int repeatCount = 0;
private Iterator<PlaylistEntry> currentIterator = null;
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
@Override
public PlaylistEntry next() {
return this.currentIterator.next();
}
};
}
}
|
if (this.currentIterator != null && this.currentIterator.hasNext()) {
return true;
}
if (this.repeatCount < REPEATS) {
this.currentIterator = baseList.iterator();
this.repeatCount++;
return true;
}
return false;
| 676
| 80
| 756
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot2/biglist/mvc/web/controller/FreeMarkerController.java
|
FreeMarkerController
|
bigListFreeMarker
|
class FreeMarkerController {
private PlaylistEntryRepository playlistEntryRepository;
public FreeMarkerController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/freemarker")
public String index() {
return "freemarker/index";
}
@RequestMapping("/smalllist.freemarker")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "freemarker/smalllist";
}
@RequestMapping("/biglist.freemarker")
public String bigListFreeMarker(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Iterator<PlaylistEntry> playlistEntries = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistEntries);
return "freemarker/biglist";
| 231
| 63
| 294
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot2/biglist/mvc/web/controller/ThymeleafController.java
|
ThymeleafController
|
bigList
|
class ThymeleafController {
private PlaylistEntryRepository playlistEntryRepository;
public ThymeleafController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping({"/", "/thymeleaf"})
public String index() {
return "thymeleaf/index";
}
@RequestMapping("/smalllist.thymeleaf")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "thymeleaf/smalllist";
}
@RequestMapping("/biglist.thymeleaf")
public String bigList(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Iterator<PlaylistEntry> playlistEntries = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistEntries);
return "thymeleaf/biglist";
| 237
| 63
| 300
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot2/biglist/webflux/BigListWebFluxAppConfig.java
|
BigListWebFluxAppConfig
|
dataSource
|
class BigListWebFluxAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(BigListWebFluxAppConfig.class);
private ApplicationContext applicationContext;
public BigListWebFluxAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 137
| 153
| 290
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot2/biglist/webflux/BigListWebFluxWebConfig.java
|
BigListWebFluxWebConfig
|
freeMarkerViewResolver
|
class BigListWebFluxWebConfig {
private ApplicationContext applicationContext;
public BigListWebFluxWebConfig(final ApplicationContext applicationContext) {
super();
this.applicationContext = applicationContext;
}
/*
* --------------------------------------------------------------------------
* FREEMARKER CONFIGURATION (no autoconf for reactive FreeMarkerViewResolver)
* --------------------------------------------------------------------------
*/
@Bean
public FreeMarkerConfigurer freeMarkerConfig() {
// Note this is the reactive version of FreeMarker's configuration, so there is no auto-configuration yet.
final FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setPreTemplateLoaders(new SpringTemplateLoader(this.applicationContext, "classpath:/templates/"));
return freeMarkerConfigurer;
}
/*
* ViewResolver for FreeMarker templates executing in NORMAL mode (only mode available for FreeMarker)
* No limit to output buffer size, all data fully resolved in context.
*/
@Bean
public FreeMarkerViewResolver freeMarkerViewResolver() {<FILL_FUNCTION_BODY>}
}
|
final FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver("", ".ftlh");
freeMarkerViewResolver.setOrder(4);
// TODO * Apparently no way to specify which views can be handled by this ViewResolver (viewNames property)
return freeMarkerViewResolver;
| 296
| 72
| 368
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot2/biglist/webflux/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
findLargeCollectionPlaylistEntries
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<PlaylistEntry> findAllPlaylistEntries() {
return this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
});
}
public Flux<PlaylistEntry> findLargeCollectionPlaylistEntries() {<FILL_FUNCTION_BODY>}
}
|
return Flux.fromIterable(
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
})).repeat(300);
| 445
| 133
| 578
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot2/biglist/webflux/web/controller/FreeMarkerController.java
|
FreeMarkerController
|
bigList
|
class FreeMarkerController {
private PlaylistEntryRepository playlistEntryRepository;
public FreeMarkerController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/freemarker")
public String index() {
return "freemarker/index";
}
@RequestMapping("/smalllist.freemarker")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "freemarker/smalllist";
}
@RequestMapping("/biglist.freemarker")
public String bigList(final Model model) {<FILL_FUNCTION_BODY>}
}
|
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "freemarker/biglist";
| 229
| 78
| 307
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot2/biglist/webflux/web/controller/ThymeleafController.java
|
ThymeleafController
|
bigListChunked
|
class ThymeleafController {
private PlaylistEntryRepository playlistEntryRepository;
public ThymeleafController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping({"/", "/thymeleaf"})
public String index() {
return "thymeleaf/index";
}
@RequestMapping("/smalllist.thymeleaf")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "thymeleaf/smalllist";
}
@RequestMapping("/biglist-datadriven.thymeleaf")
public String bigListDataDriven(final Model model) {
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
// No need to fully resolve the Publisher! We will just let it drive
model.addAttribute("dataSource", new ReactiveDataDriverContextVariable(playlistStream, 1000));
return "thymeleaf/biglist-datadriven";
}
@RequestMapping("/biglist-chunked.thymeleaf")
public String bigListChunked(final Model model) {<FILL_FUNCTION_BODY>}
@RequestMapping("/biglist-full.thymeleaf")
public String bigListFull(final Model model) {
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "thymeleaf/biglist-full";
}
}
|
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "thymeleaf/biglist-chunked";
| 487
| 82
| 569
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-sse-webflux/src/main/java/org/thymeleaf/examples/springboot2/sse/webflux/SSEWebFluxAppConfig.java
|
SSEWebFluxAppConfig
|
dataSource
|
class SSEWebFluxAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SSEWebFluxAppConfig.class);
private ApplicationContext applicationContext;
public SSEWebFluxAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 137
| 153
| 290
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-sse-webflux/src/main/java/org/thymeleaf/examples/springboot2/sse/webflux/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
findLargeCollectionPlaylistEntries
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Flux<PlaylistEntry> findLargeCollectionPlaylistEntries() {<FILL_FUNCTION_BODY>}
}
|
return Flux.fromIterable(
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
})).repeat(300).delayElements(Duration.ofSeconds(1L));
| 309
| 145
| 454
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-sse-webflux/src/main/java/org/thymeleaf/examples/springboot2/sse/webflux/web/controller/SSEController.java
|
SSEController
|
events
|
class SSEController {
private PlaylistEntryRepository playlistEntryRepository;
public SSEController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/events")
public String events(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
final IReactiveDataDriverContextVariable dataDriver =
new ReactiveDataDriverContextVariable(playlistStream, 1, 1);
model.addAttribute("data", dataDriver);
return "events";
| 147
| 88
| 235
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot2/stsm/mvc/business/entities/Row.java
|
Row
|
toString
|
class Row {
private Variety variety = null;
private Integer seedsPerCell = null;
public Row() {
super();
}
public Variety getVariety() {
return this.variety;
}
public void setVariety(final Variety variety) {
this.variety = variety;
}
public Integer getSeedsPerCell() {
return this.seedsPerCell;
}
public void setSeedsPerCell(final Integer seedsPerCell) {
this.seedsPerCell = seedsPerCell;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
| 186
| 36
| 222
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot2/stsm/mvc/business/entities/SeedStarter.java
|
SeedStarter
|
toString
|
class SeedStarter {
private Integer id = null;
private Date datePlanted = null;
private Boolean covered = null;
private Type type = Type.PLASTIC;
private Feature[] features = null;
private List<Row> rows = new ArrayList<Row>();
public SeedStarter() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(final Integer id) {
this.id = id;
}
public Date getDatePlanted() {
return this.datePlanted;
}
public void setDatePlanted(final Date datePlanted) {
this.datePlanted = datePlanted;
}
public Boolean getCovered() {
return this.covered;
}
public void setCovered(final Boolean covered) {
this.covered = covered;
}
public Type getType() {
return this.type;
}
public void setType(final Type type) {
this.type = type;
}
public Feature[] getFeatures() {
return this.features;
}
public void setFeatures(final Feature[] features) {
this.features = features;
}
public List<Row> getRows() {
return this.rows;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted
+ ", covered=" + this.covered + ", type=" + this.type + ", features="
+ Arrays.toString(this.features) + ", rows=" + this.rows + "]";
| 388
| 83
| 471
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot2/stsm/mvc/web/controller/SeedStarterMngController.java
|
SeedStarterMngController
|
saveSeedstarter
|
class SeedStarterMngController {
private VarietyService varietyService;
private SeedStarterService seedStarterService;
public SeedStarterMngController() {
super();
}
@Autowired
public void setVarietyService(final VarietyService varietyService) {
this.varietyService = varietyService;
}
@Autowired
public void setSeedStarterService(final SeedStarterService seedStarterService) {
this.seedStarterService = seedStarterService;
}
@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public List<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public List<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}
@RequestMapping({"/","/seedstartermng"})
public String showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"save"})
public String saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult) {<FILL_FUNCTION_BODY>}
@RequestMapping(value="/seedstartermng", params={"addRow"})
public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"removeRow"})
public String removeRow(
final SeedStarter seedStarter,
final BindingResult bindingResult,
@RequestParam(value = "removeRow", required = false) Integer rowId) {
seedStarter.getRows().remove(rowId.intValue());
return "seedstartermng";
}
}
|
if (bindingResult.hasErrors()) {
return "seedstartermng";
}
this.seedStarterService.add(seedStarter);
return "redirect:/seedstartermng";
| 633
| 53
| 686
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot2/stsm/mvc/web/conversion/DateFormatter.java
|
DateFormatter
|
createDateFormat
|
class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>}
}
|
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
| 170
| 57
| 227
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot2/stsm/webflux/business/entities/Row.java
|
Row
|
toString
|
class Row {
private Variety variety = null;
private Integer seedsPerCell = null;
public Row() {
super();
}
public Variety getVariety() {
return this.variety;
}
public void setVariety(final Variety variety) {
this.variety = variety;
}
public Integer getSeedsPerCell() {
return this.seedsPerCell;
}
public void setSeedsPerCell(final Integer seedsPerCell) {
this.seedsPerCell = seedsPerCell;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
| 186
| 36
| 222
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot2/stsm/webflux/business/entities/SeedStarter.java
|
SeedStarter
|
toString
|
class SeedStarter {
private Integer id = null;
private Date datePlanted = null;
private Boolean covered = null;
private Type type = Type.PLASTIC;
private Feature[] features = null;
private List<Row> rows = new ArrayList<Row>();
public SeedStarter() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(final Integer id) {
this.id = id;
}
public Date getDatePlanted() {
return this.datePlanted;
}
public void setDatePlanted(final Date datePlanted) {
this.datePlanted = datePlanted;
}
public Boolean getCovered() {
return this.covered;
}
public void setCovered(final Boolean covered) {
this.covered = covered;
}
public Type getType() {
return this.type;
}
public void setType(final Type type) {
this.type = type;
}
public Feature[] getFeatures() {
return this.features;
}
public void setFeatures(final Feature[] features) {
this.features = features;
}
public List<Row> getRows() {
return this.rows;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted
+ ", covered=" + this.covered + ", type=" + this.type + ", features="
+ Arrays.toString(this.features) + ", rows=" + this.rows + "]";
| 389
| 83
| 472
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot2/stsm/webflux/web/controller/SeedStarterMngController.java
|
SeedStarterMngController
|
doSeedstarter
|
class SeedStarterMngController {
private VarietyService varietyService;
private SeedStarterService seedStarterService;
public SeedStarterMngController() {
super();
}
@Autowired
public void setVarietyService(final VarietyService varietyService) {
this.varietyService = varietyService;
}
@Autowired
public void setSeedStarterService(final SeedStarterService seedStarterService) {
this.seedStarterService = seedStarterService;
}
@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public Flux<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public Flux<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}
/*
* NOTE that in this reactive version of STSM we cannot select the controller method to be executed
* depending on the presence of a specific request parameter (using the "param" attribute of the
* @RequestMapping annotation) because WebFlux does not include as "request parameters" data
* coming from forms (see https://jira.spring.io/browse/SPR-15508 ). Doing so would mean blocking
* for the time the framework needs for reading the request payload, which goes against the
* general reactiveness of the architecture.
*
* So the ways to access data from form are, either include then as a part of form-backing bean
* (in this case SeedStarter), or using exchange.getFormData(). In this case, modifying a model entity
* like SeedStarter because of a very specific need of the user interface (adding the "save",
* "addRow" or "removeRow" parameters in order to modify the form's structure from the server) would
* not be very elegant, so instead we will read exchange.getFormData() and direct to a different
* inner (private) controller method depending on the presence of these fields in the form data
* coming from the client.
*/
@RequestMapping({"/","/seedstartermng"})
public Mono<String> doSeedstarter(
final SeedStarter seedStarter, final BindingResult bindingResult, final ServerWebExchange exchange) {<FILL_FUNCTION_BODY>}
private Mono<String> showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return Mono.just("seedstartermng");
}
private Mono<String> saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Mono.just("seedstartermng");
}
return this.seedStarterService.add(seedStarter).then(Mono.just("redirect:/seedstartermng"));
}
private Mono<String> addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return Mono.just("seedstartermng");
}
private Mono<String> removeRow(
final SeedStarter seedStarter,
final BindingResult bindingResult,
final int rowId) {
seedStarter.getRows().remove(rowId);
return Mono.just("seedstartermng");
}
}
|
return exchange.getFormData().flatMap(
formData -> {
if (formData.containsKey("save")) {
return saveSeedstarter(seedStarter, bindingResult);
}
if (formData.containsKey("addRow")) {
return addRow(seedStarter, bindingResult);
}
if (formData.containsKey("removeRow")) {
final int rowId = Integer.parseInt(formData.getFirst("removeRow"));
return removeRow(seedStarter, bindingResult, rowId);
}
return showSeedstarters(seedStarter);
});
| 975
| 157
| 1,132
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot2/stsm/webflux/web/conversion/DateFormatter.java
|
DateFormatter
|
createDateFormat
|
class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>}
}
|
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
| 170
| 57
| 227
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot2/thymeleaf-examples-springboot2-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot2/stsm/webflux/web/conversion/VarietyFormatter.java
|
VarietyFormatter
|
parse
|
class VarietyFormatter implements Formatter<Variety> {
@Autowired
private VarietyService varietyService;
public VarietyFormatter() {
super();
}
public Variety parse(final String text, final Locale locale) throws ParseException {<FILL_FUNCTION_BODY>}
public String print(final Variety object, final Locale locale) {
return (object != null ? object.getId().toString() : "");
}
}
|
final Integer varietyId = Integer.valueOf(text);
// There is no Formatter API yet that allows us to return a Publisher, so we need to block
return this.varietyService.findById(varietyId).block();
| 125
| 59
| 184
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot3/biglist/mvc/BigListMvcAppConfig.java
|
BigListMvcAppConfig
|
dataSource
|
class BigListMvcAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(BigListMvcAppConfig.class);
private ApplicationContext applicationContext;
public BigListMvcAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 134
| 153
| 287
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot3/biglist/mvc/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
findLargeCollectionPlaylistEntries
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Iterator<PlaylistEntry> findAllPlaylistEntries() {
return this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
}).iterator();
}
public Iterator<PlaylistEntry> findLargeCollectionPlaylistEntries() {<FILL_FUNCTION_BODY>}
}
|
final List<PlaylistEntry> baseList =
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
});
return new Iterator<PlaylistEntry>() {
private static final int REPEATS = 300;
private int repeatCount = 0;
private Iterator<PlaylistEntry> currentIterator = null;
@Override
public boolean hasNext() {
if (this.currentIterator != null && this.currentIterator.hasNext()) {
return true;
}
if (this.repeatCount < REPEATS) {
this.currentIterator = baseList.iterator();
this.repeatCount++;
return true;
}
return false;
}
@Override
public PlaylistEntry next() {
return this.currentIterator.next();
}
};
| 449
| 307
| 756
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot3/biglist/mvc/web/controller/FreeMarkerController.java
|
FreeMarkerController
|
bigListFreeMarker
|
class FreeMarkerController {
private PlaylistEntryRepository playlistEntryRepository;
public FreeMarkerController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/freemarker")
public String index() {
return "freemarker/index";
}
@RequestMapping("/smalllist.freemarker")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "freemarker/smalllist";
}
@RequestMapping("/biglist.freemarker")
public String bigListFreeMarker(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Iterator<PlaylistEntry> playlistEntries = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistEntries);
return "freemarker/biglist";
| 231
| 63
| 294
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot3/biglist/mvc/web/controller/ThymeleafController.java
|
ThymeleafController
|
bigList
|
class ThymeleafController {
private PlaylistEntryRepository playlistEntryRepository;
public ThymeleafController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping({"/", "/thymeleaf"})
public String index() {
return "thymeleaf/index";
}
@RequestMapping("/smalllist.thymeleaf")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "thymeleaf/smalllist";
}
@RequestMapping("/biglist.thymeleaf")
public String bigList(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Iterator<PlaylistEntry> playlistEntries = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistEntries);
return "thymeleaf/biglist";
| 237
| 63
| 300
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot3/biglist/webflux/BigListWebFluxAppConfig.java
|
BigListWebFluxAppConfig
|
dataSource
|
class BigListWebFluxAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(BigListWebFluxAppConfig.class);
private ApplicationContext applicationContext;
public BigListWebFluxAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 137
| 153
| 290
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot3/biglist/webflux/BigListWebFluxWebConfig.java
|
BigListWebFluxWebConfig
|
freeMarkerConfig
|
class BigListWebFluxWebConfig {
private ApplicationContext applicationContext;
public BigListWebFluxWebConfig(final ApplicationContext applicationContext) {
super();
this.applicationContext = applicationContext;
}
/*
* --------------------------------------------------------------------------
* FREEMARKER CONFIGURATION (no autoconf for reactive FreeMarkerViewResolver)
* --------------------------------------------------------------------------
*/
@Bean
public FreeMarkerConfigurer freeMarkerConfig() {<FILL_FUNCTION_BODY>}
/*
* ViewResolver for FreeMarker templates executing in NORMAL mode (only mode available for FreeMarker)
* No limit to output buffer size, all data fully resolved in context.
*/
@Bean
public FreeMarkerViewResolver freeMarkerViewResolver() {
final FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver("", ".ftlh");
freeMarkerViewResolver.setOrder(4);
// TODO * Apparently no way to specify which views can be handled by this ViewResolver (viewNames property)
return freeMarkerViewResolver;
}
}
|
// Note this is the reactive version of FreeMarker's configuration, so there is no auto-configuration yet.
final FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setPreTemplateLoaders(new SpringTemplateLoader(this.applicationContext, "classpath:/templates/"));
return freeMarkerConfigurer;
| 277
| 91
| 368
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot3/biglist/webflux/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
findLargeCollectionPlaylistEntries
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<PlaylistEntry> findAllPlaylistEntries() {
return this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
});
}
public Flux<PlaylistEntry> findLargeCollectionPlaylistEntries() {<FILL_FUNCTION_BODY>}
}
|
return Flux.fromIterable(
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
})).repeat(300);
| 445
| 133
| 578
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot3/biglist/webflux/web/controller/FreeMarkerController.java
|
FreeMarkerController
|
bigList
|
class FreeMarkerController {
private PlaylistEntryRepository playlistEntryRepository;
public FreeMarkerController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/freemarker")
public String index() {
return "freemarker/index";
}
@RequestMapping("/smalllist.freemarker")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "freemarker/smalllist";
}
@RequestMapping("/biglist.freemarker")
public String bigList(final Model model) {<FILL_FUNCTION_BODY>}
}
|
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "freemarker/biglist";
| 229
| 78
| 307
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-webflux/src/main/java/org/thymeleaf/examples/springboot3/biglist/webflux/web/controller/ThymeleafController.java
|
ThymeleafController
|
bigListFull
|
class ThymeleafController {
private PlaylistEntryRepository playlistEntryRepository;
public ThymeleafController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping({"/", "/thymeleaf"})
public String index() {
return "thymeleaf/index";
}
@RequestMapping("/smalllist.thymeleaf")
public String smallList(final Model model) {
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries());
return "thymeleaf/smalllist";
}
@RequestMapping("/biglist-datadriven.thymeleaf")
public String bigListDataDriven(final Model model) {
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
// No need to fully resolve the Publisher! We will just let it drive
model.addAttribute("dataSource", new ReactiveDataDriverContextVariable(playlistStream, 1000));
return "thymeleaf/biglist-datadriven";
}
@RequestMapping("/biglist-chunked.thymeleaf")
public String bigListChunked(final Model model) {
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "thymeleaf/biglist-chunked";
}
@RequestMapping("/biglist-full.thymeleaf")
public String bigListFull(final Model model) {<FILL_FUNCTION_BODY>}
}
|
// Will be async resolved by Spring WebFlux before calling the view
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
model.addAttribute("dataSource", playlistStream);
return "thymeleaf/biglist-full";
| 489
| 80
| 569
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-sse-webflux/src/main/java/org/thymeleaf/examples/springboot3/sse/webflux/SSEWebFluxAppConfig.java
|
SSEWebFluxAppConfig
|
dataSource
|
class SSEWebFluxAppConfig implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SSEWebFluxAppConfig.class);
private ApplicationContext applicationContext;
public SSEWebFluxAppConfig() {
super();
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
try {
final Resource dbResource = this.applicationContext.getResource("classpath:data/chinook.sqlite");
logger.debug("Database path: " + dbResource.getURL().getPath());
final DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:" + dbResource.getURL().getPath());
return dataSourceBuilder.build();
} catch (final IOException e) {
throw new ApplicationContextException("Error initializing database", e);
}
| 137
| 153
| 290
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-sse-webflux/src/main/java/org/thymeleaf/examples/springboot3/sse/webflux/business/repository/PlaylistEntryRepository.java
|
PlaylistEntryRepository
|
findLargeCollectionPlaylistEntries
|
class PlaylistEntryRepository {
private static final String QUERY_FIND_ALL_PLAYLIST_ENTRIES =
"SELECT p.PlaylistId as 'playlistID', " +
" p.Name as 'playlistName', " +
" t.Name as 'trackName', " +
" ar.Name as 'artistName', " +
" a.title as 'albumTitle' " +
"FROM playlist p, PlaylistTrack pt, track t, Album a, Artist ar " +
"WHERE p.PlaylistId = pt.PlaylistId AND " +
" pt.TrackId = t.TrackId AND " +
" t.AlbumId = a.AlbumId AND " +
" a.ArtistId = ar.ArtistId";
private JdbcTemplate jdbcTemplate;
public PlaylistEntryRepository() {
super();
}
@Autowired
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Flux<PlaylistEntry> findLargeCollectionPlaylistEntries() {<FILL_FUNCTION_BODY>}
}
|
return Flux.fromIterable(
this.jdbcTemplate.query(
QUERY_FIND_ALL_PLAYLIST_ENTRIES,
(resultSet, i) -> {
return new PlaylistEntry(
Integer.valueOf(resultSet.getInt("playlistID")),
resultSet.getString("playlistName"),
resultSet.getString("trackName"),
resultSet.getString("artistName"),
resultSet.getString("albumTitle"));
})).repeat(300).delayElements(Duration.ofSeconds(1L));
| 309
| 145
| 454
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-sse-webflux/src/main/java/org/thymeleaf/examples/springboot3/sse/webflux/web/controller/SSEController.java
|
SSEController
|
events
|
class SSEController {
private PlaylistEntryRepository playlistEntryRepository;
public SSEController() {
super();
}
@Autowired
public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) {
this.playlistEntryRepository = playlistEntryRepository;
}
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/events")
public String events(final Model model) {<FILL_FUNCTION_BODY>}
}
|
final Flux<PlaylistEntry> playlistStream = this.playlistEntryRepository.findLargeCollectionPlaylistEntries();
final IReactiveDataDriverContextVariable dataDriver =
new ReactiveDataDriverContextVariable(playlistStream, 1, 1);
model.addAttribute("data", dataDriver);
return "events";
| 147
| 88
| 235
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot3/stsm/mvc/business/entities/Row.java
|
Row
|
toString
|
class Row {
private Variety variety = null;
private Integer seedsPerCell = null;
public Row() {
super();
}
public Variety getVariety() {
return this.variety;
}
public void setVariety(final Variety variety) {
this.variety = variety;
}
public Integer getSeedsPerCell() {
return this.seedsPerCell;
}
public void setSeedsPerCell(final Integer seedsPerCell) {
this.seedsPerCell = seedsPerCell;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
| 186
| 36
| 222
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot3/stsm/mvc/business/entities/SeedStarter.java
|
SeedStarter
|
toString
|
class SeedStarter {
private Integer id = null;
private Date datePlanted = null;
private Boolean covered = null;
private Type type = Type.PLASTIC;
private Feature[] features = null;
private List<Row> rows = new ArrayList<Row>();
public SeedStarter() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(final Integer id) {
this.id = id;
}
public Date getDatePlanted() {
return this.datePlanted;
}
public void setDatePlanted(final Date datePlanted) {
this.datePlanted = datePlanted;
}
public Boolean getCovered() {
return this.covered;
}
public void setCovered(final Boolean covered) {
this.covered = covered;
}
public Type getType() {
return this.type;
}
public void setType(final Type type) {
this.type = type;
}
public Feature[] getFeatures() {
return this.features;
}
public void setFeatures(final Feature[] features) {
this.features = features;
}
public List<Row> getRows() {
return this.rows;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted
+ ", covered=" + this.covered + ", type=" + this.type + ", features="
+ Arrays.toString(this.features) + ", rows=" + this.rows + "]";
| 388
| 83
| 471
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot3/stsm/mvc/web/controller/SeedStarterMngController.java
|
SeedStarterMngController
|
saveSeedstarter
|
class SeedStarterMngController {
private VarietyService varietyService;
private SeedStarterService seedStarterService;
public SeedStarterMngController() {
super();
}
@Autowired
public void setVarietyService(final VarietyService varietyService) {
this.varietyService = varietyService;
}
@Autowired
public void setSeedStarterService(final SeedStarterService seedStarterService) {
this.seedStarterService = seedStarterService;
}
@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public List<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public List<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}
@RequestMapping({"/","/seedstartermng"})
public String showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"save"})
public String saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult) {<FILL_FUNCTION_BODY>}
@RequestMapping(value="/seedstartermng", params={"addRow"})
public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"removeRow"})
public String removeRow(
final SeedStarter seedStarter,
final BindingResult bindingResult,
@RequestParam(value = "removeRow", required = false) Integer rowId) {
seedStarter.getRows().remove(rowId.intValue());
return "seedstartermng";
}
}
|
if (bindingResult.hasErrors()) {
return "seedstartermng";
}
this.seedStarterService.add(seedStarter);
return "redirect:/seedstartermng";
| 633
| 53
| 686
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot3/stsm/mvc/web/conversion/DateFormatter.java
|
DateFormatter
|
createDateFormat
|
class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>}
}
|
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
| 170
| 57
| 227
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot3/stsm/webflux/business/entities/Row.java
|
Row
|
toString
|
class Row {
private Variety variety = null;
private Integer seedsPerCell = null;
public Row() {
super();
}
public Variety getVariety() {
return this.variety;
}
public void setVariety(final Variety variety) {
this.variety = variety;
}
public Integer getSeedsPerCell() {
return this.seedsPerCell;
}
public void setSeedsPerCell(final Integer seedsPerCell) {
this.seedsPerCell = seedsPerCell;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
| 186
| 36
| 222
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot3/stsm/webflux/business/entities/SeedStarter.java
|
SeedStarter
|
toString
|
class SeedStarter {
private Integer id = null;
private Date datePlanted = null;
private Boolean covered = null;
private Type type = Type.PLASTIC;
private Feature[] features = null;
private List<Row> rows = new ArrayList<Row>();
public SeedStarter() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(final Integer id) {
this.id = id;
}
public Date getDatePlanted() {
return this.datePlanted;
}
public void setDatePlanted(final Date datePlanted) {
this.datePlanted = datePlanted;
}
public Boolean getCovered() {
return this.covered;
}
public void setCovered(final Boolean covered) {
this.covered = covered;
}
public Type getType() {
return this.type;
}
public void setType(final Type type) {
this.type = type;
}
public Feature[] getFeatures() {
return this.features;
}
public void setFeatures(final Feature[] features) {
this.features = features;
}
public List<Row> getRows() {
return this.rows;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted
+ ", covered=" + this.covered + ", type=" + this.type + ", features="
+ Arrays.toString(this.features) + ", rows=" + this.rows + "]";
| 389
| 83
| 472
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot3/stsm/webflux/web/controller/SeedStarterMngController.java
|
SeedStarterMngController
|
doSeedstarter
|
class SeedStarterMngController {
private VarietyService varietyService;
private SeedStarterService seedStarterService;
public SeedStarterMngController() {
super();
}
@Autowired
public void setVarietyService(final VarietyService varietyService) {
this.varietyService = varietyService;
}
@Autowired
public void setSeedStarterService(final SeedStarterService seedStarterService) {
this.seedStarterService = seedStarterService;
}
@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public Flux<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public Flux<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}
/*
* NOTE that in this reactive version of STSM we cannot select the controller method to be executed
* depending on the presence of a specific request parameter (using the "param" attribute of the
* @RequestMapping annotation) because WebFlux does not include as "request parameters" data
* coming from forms (see https://jira.spring.io/browse/SPR-15508 ). Doing so would mean blocking
* for the time the framework needs for reading the request payload, which goes against the
* general reactiveness of the architecture.
*
* So the ways to access data from form are, either include then as a part of form-backing bean
* (in this case SeedStarter), or using exchange.getFormData(). In this case, modifying a model entity
* like SeedStarter because of a very specific need of the user interface (adding the "save",
* "addRow" or "removeRow" parameters in order to modify the form's structure from the server) would
* not be very elegant, so instead we will read exchange.getFormData() and direct to a different
* inner (private) controller method depending on the presence of these fields in the form data
* coming from the client.
*/
@RequestMapping({"/","/seedstartermng"})
public Mono<String> doSeedstarter(
final SeedStarter seedStarter, final BindingResult bindingResult, final ServerWebExchange exchange) {<FILL_FUNCTION_BODY>}
private Mono<String> showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return Mono.just("seedstartermng");
}
private Mono<String> saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Mono.just("seedstartermng");
}
return this.seedStarterService.add(seedStarter).then(Mono.just("redirect:/seedstartermng"));
}
private Mono<String> addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return Mono.just("seedstartermng");
}
private Mono<String> removeRow(
final SeedStarter seedStarter,
final BindingResult bindingResult,
final int rowId) {
seedStarter.getRows().remove(rowId);
return Mono.just("seedstartermng");
}
}
|
return exchange.getFormData().flatMap(
formData -> {
if (formData.containsKey("save")) {
return saveSeedstarter(seedStarter, bindingResult);
}
if (formData.containsKey("addRow")) {
return addRow(seedStarter, bindingResult);
}
if (formData.containsKey("removeRow")) {
final int rowId = Integer.parseInt(formData.getFirst("removeRow"));
return removeRow(seedStarter, bindingResult, rowId);
}
return showSeedstarters(seedStarter);
});
| 975
| 157
| 1,132
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot3/stsm/webflux/web/conversion/DateFormatter.java
|
DateFormatter
|
createDateFormat
|
class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>}
}
|
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
| 170
| 57
| 227
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-stsm-webflux/src/main/java/org/thymeleaf/examples/springboot3/stsm/webflux/web/conversion/VarietyFormatter.java
|
VarietyFormatter
|
parse
|
class VarietyFormatter implements Formatter<Variety> {
@Autowired
private VarietyService varietyService;
public VarietyFormatter() {
super();
}
public Variety parse(final String text, final Locale locale) throws ParseException {<FILL_FUNCTION_BODY>}
public String print(final Variety object, final Locale locale) {
return (object != null ? object.getId().toString() : "");
}
}
|
final Integer varietyId = Integer.valueOf(text);
// There is no Formatter API yet that allows us to return a Publisher, so we need to block
return this.varietyService.findById(varietyId).block();
| 125
| 59
| 184
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity5/thymeleaf-examples-springsecurity5-websecurity/src/main/java/org/thymeleaf/examples/springsecurity5/websecurity/SpringWebApplicationInitializer.java
|
SpringWebApplicationInitializer
|
getServletFilters
|
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public static final String CHARACTER_ENCODING = "UTF-8";
public SpringWebApplicationInitializer() {
super();
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { SpringWebConfig.class, SpringSecurityConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>}
}
|
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding(CHARACTER_ENCODING);
encodingFilter.setForceEncoding(true);
return new Filter[] { encodingFilter };
| 191
| 55
| 246
|
<methods>public void <init>() <variables>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity5/thymeleaf-examples-springsecurity5-websecurity/src/main/java/org/thymeleaf/examples/springsecurity5/websecurity/security/SpringSecurityConfig.java
|
SpringSecurityConfig
|
filterChain
|
class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
@Bean
public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
return new InMemoryUserDetailsManager(
User.withUsername("jim").password("{noop}demo").roles("ADMIN").build(),
User.withUsername("bob").password("{noop}demo").roles("USER").build(),
User.withUsername("ted").password("{noop}demo").roles("USER","ADMIN").build());
}
}
|
http
.formLogin()
.loginPage("/login.html")
.failureUrl("/login-error.html")
.and()
.logout()
.logoutSuccessUrl("/index.html")
.and()
.authorizeRequests()
.mvcMatchers("/admin/**").hasRole("ADMIN")
.mvcMatchers("/user/**").hasRole("USER")
.mvcMatchers("/shared/**").hasAnyRole("USER","ADMIN")
.and()
.exceptionHandling()
.accessDeniedPage("/403.html");
return http.build();
| 177
| 157
| 334
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity5/thymeleaf-examples-springsecurity5-websecurity/src/main/java/org/thymeleaf/examples/springsecurity5/websecurity/web/SpringWebConfig.java
|
SpringWebConfig
|
templateResolver
|
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
public SpringWebConfig() {
super();
}
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setBasename("Messages");
return resourceBundleMessageSource;
}
/* **************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS */
/* TemplateResolver <- TemplateEngine <- ViewResolver */
/* **************************************************************** */
@Bean
public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
/* ******************************************************************* */
/* Defines callback methods to customize the Java-based configuration */
/* for Spring MVC enabled via {@code @EnableWebMvc} */
/* ******************************************************************* */
/**
* Dispatcher configuration for serving static resources
*/
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
|
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
| 559
| 120
| 679
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity5/thymeleaf-examples-springsecurity5-websecurity/src/main/java/org/thymeleaf/examples/springsecurity5/websecurity/web/controller/ErrorController.java
|
ErrorController
|
exception
|
class ErrorController {
private static Logger logger = LoggerFactory.getLogger(ErrorController.class);
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String exception(final Throwable throwable, final Model model) {<FILL_FUNCTION_BODY>}
}
|
logger.error("Exception during execution of SpringSecurity application", throwable);
String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
model.addAttribute("errorMessage", errorMessage);
model.addAttribute("httpStatus", HttpStatus.INTERNAL_SERVER_ERROR);
return "error";
| 88
| 83
| 171
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity5/thymeleaf-examples-springsecurity5-websecurity/src/main/java/org/thymeleaf/examples/springsecurity5/websecurity/web/controller/MainController.java
|
MainController
|
error
|
class MainController {
@RequestMapping("/")
public String root(Locale locale) {
return "redirect:/index.html";
}
/** Home page. */
@RequestMapping("/index.html")
public String index() {
return "index";
}
/** User zone index. */
@RequestMapping("/user/index.html")
public String userIndex() {
return "user/index";
}
/** Administration zone index. */
@RequestMapping("/admin/index.html")
public String adminIndex() {
return "admin/index";
}
/** Shared zone index. */
@RequestMapping("/shared/index.html")
public String sharedIndex() {
return "shared/index";
}
/** Login form. */
@RequestMapping("/login.html")
public String login() {
return "login";
}
/** Login form with error. */
@RequestMapping("/login-error.html")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
/** Simulation of an exception. */
@RequestMapping("/simulateError.html")
public void simulateError() {
throw new RuntimeException("This is a simulated error message");
}
/** Error page. */
@RequestMapping("/error.html")
public String error(HttpServletRequest request, Model model) {<FILL_FUNCTION_BODY>}
/** Error page. */
@RequestMapping("/403.html")
public String forbidden() {
return "403";
}
}
|
model.addAttribute("errorCode", "Error " + request.getAttribute("javax.servlet.error.status_code"));
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("<ul>");
while (throwable != null) {
errorMessage.append("<li>").append(HtmlEscape.escapeHtml5(throwable.getMessage())).append("</li>");
throwable = throwable.getCause();
}
errorMessage.append("</ul>");
model.addAttribute("errorMessage", errorMessage.toString());
return "error";
| 416
| 176
| 592
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity6/thymeleaf-examples-springsecurity6-websecurity/src/main/java/org/thymeleaf/examples/springsecurity6/websecurity/SpringWebApplicationInitializer.java
|
SpringWebApplicationInitializer
|
getServletFilters
|
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public static final String CHARACTER_ENCODING = "UTF-8";
public SpringWebApplicationInitializer() {
super();
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { ApplicationConfiguration.class };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>}
}
|
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding(CHARACTER_ENCODING);
encodingFilter.setForceEncoding(true);
return new Filter[] { encodingFilter };
| 184
| 55
| 239
|
<methods>public void <init>() <variables>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity6/thymeleaf-examples-springsecurity6-websecurity/src/main/java/org/thymeleaf/examples/springsecurity6/websecurity/security/SpringSecurityConfig.java
|
SpringSecurityConfig
|
filterChain
|
class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
@Bean
public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
return new InMemoryUserDetailsManager(
User.withUsername("jim").password("{noop}demo").roles("ADMIN").build(),
User.withUsername("bob").password("{noop}demo").roles("USER").build(),
User.withUsername("ted").password("{noop}demo").roles("USER","ADMIN").build());
}
}
|
http
.formLogin(formLogin -> formLogin
.loginPage("/login.html")
.failureUrl("/login-error.html"))
.logout(logout -> logout
.logoutSuccessUrl("/index.html"))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(
new AntPathRequestMatcher("/"),
new AntPathRequestMatcher("/index.html"),
new AntPathRequestMatcher("/login.html"),
new AntPathRequestMatcher("/css/**"),
new AntPathRequestMatcher("/favicon.ico")).permitAll()
.requestMatchers(new AntPathRequestMatcher("/admin/**")).hasRole("ADMIN")
.requestMatchers(new AntPathRequestMatcher("/user/**")).hasRole("USER")
.requestMatchers(new AntPathRequestMatcher("/shared/**")).hasAnyRole("USER","ADMIN")
.anyRequest().authenticated())
.exceptionHandling(handling -> handling
.accessDeniedPage("/403.html"));
return http.build();
| 177
| 272
| 449
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity6/thymeleaf-examples-springsecurity6-websecurity/src/main/java/org/thymeleaf/examples/springsecurity6/websecurity/web/SpringWebConfig.java
|
SpringWebConfig
|
templateResolver
|
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
public SpringWebConfig() {
super();
}
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setBasename("Messages");
return resourceBundleMessageSource;
}
/* **************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS */
/* TemplateResolver <- TemplateEngine <- ViewResolver */
/* **************************************************************** */
@Bean
public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
/* ******************************************************************* */
/* Defines callback methods to customize the Java-based configuration */
/* for Spring MVC enabled via {@code @EnableWebMvc} */
/* ******************************************************************* */
/**
* Dispatcher configuration for serving static resources
*/
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
|
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
| 559
| 120
| 679
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity6/thymeleaf-examples-springsecurity6-websecurity/src/main/java/org/thymeleaf/examples/springsecurity6/websecurity/web/controller/ErrorController.java
|
ErrorController
|
exception
|
class ErrorController {
private static Logger logger = LoggerFactory.getLogger(ErrorController.class);
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String exception(final Throwable throwable, final Model model) {<FILL_FUNCTION_BODY>}
}
|
logger.error("Exception during execution of SpringSecurity application", throwable);
String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
model.addAttribute("errorMessage", errorMessage);
model.addAttribute("httpStatus", HttpStatus.INTERNAL_SERVER_ERROR);
return "error";
| 88
| 83
| 171
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/examples/springsecurity6/thymeleaf-examples-springsecurity6-websecurity/src/main/java/org/thymeleaf/examples/springsecurity6/websecurity/web/controller/MainController.java
|
MainController
|
error
|
class MainController {
@RequestMapping("/")
public String root(Locale locale) {
return "redirect:/index.html";
}
/** Home page. */
@RequestMapping("/index.html")
public String index() {
return "index";
}
/** User zone index. */
@RequestMapping("/user/index.html")
public String userIndex() {
return "user/index";
}
/** Administration zone index. */
@RequestMapping("/admin/index.html")
public String adminIndex() {
return "admin/index";
}
/** Shared zone index. */
@RequestMapping("/shared/index.html")
public String sharedIndex() {
return "shared/index";
}
/** Login form. */
@RequestMapping("/login.html")
public String login() {
return "login";
}
/** Login form with error. */
@RequestMapping("/login-error.html")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
/** Simulation of an exception. */
@RequestMapping("/simulateError.html")
public void simulateError() {
throw new RuntimeException("This is a simulated error message");
}
/** Error page. */
@RequestMapping("/error.html")
public String error(HttpServletRequest request, Model model) {<FILL_FUNCTION_BODY>}
/** Error page. */
@RequestMapping("/403.html")
public String forbidden() {
return "403";
}
}
|
model.addAttribute("errorCode", "Error " + request.getAttribute("javax.servlet.error.status_code"));
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("<ul>");
while (throwable != null) {
errorMessage.append("<li>").append(HtmlEscape.escapeHtml5(throwable.getMessage())).append("</li>");
throwable = throwable.getCause();
}
errorMessage.append("</ul>");
model.addAttribute("errorMessage", errorMessage.toString());
return "error";
| 416
| 176
| 592
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/auth/AclAuthUtils.java
|
AclAuthUtils
|
parsePermissionsString
|
class AclAuthUtils {
private static final Logger logger = LoggerFactory.getLogger(AclAuthUtils.class);
private AclAuthUtils() {
super();
}
public static boolean authorizeUsingAccessControlList(
final IExpressionContext context,
final Object domainObject,
final ApplicationContext applicationContext, final String permissionsString,
final Authentication authentication) {
final List<Permission> permissions =
parsePermissionsString(applicationContext, permissionsString);
return authorizeUsingAccessControlList(context, domainObject, permissions, authentication);
}
public static boolean authorizeUsingAccessControlList(
final IExpressionContext context,
final Object domainObject, final List<Permission> permissions,
final Authentication authentication) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checking authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\".",
new Object[] {TemplateEngine.threadIndex(), (authentication == null? null : authentication.getName()),
(domainObject == null? null : domainObject.getClass().getName()), permissions});
}
final ApplicationContext applicationContext = AuthUtils.getContext(context);
final AclService aclService = getBeanOfType(applicationContext, AclService.class);
if (authentication == null) {
// If authentication is null, authorization cannot be granted.
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Authentication object is null. Access is DENIED. ",
new Object[] {TemplateEngine.threadIndex()});
}
return false;
}
/*
* Initialize required objects
*/
SidRetrievalStrategy sidRetrievalStrategy = getBeanOfType(applicationContext, SidRetrievalStrategy.class);
if (sidRetrievalStrategy == null) {
sidRetrievalStrategy = new SidRetrievalStrategyImpl();
}
ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = getBeanOfType(applicationContext, ObjectIdentityRetrievalStrategy.class);
if (objectIdentityRetrievalStrategy == null) {
objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
}
/*
* Compute permissions
*/
if ((null == permissions) || permissions.isEmpty()) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Permissions are null or empty. Access is DENIED. ",
new Object[] {TemplateEngine.threadIndex()});
}
return false;
}
if (domainObject == null) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Domain object for resolved to null. Access by " +
"Access Control List is GRANTED.", new Object[] {TemplateEngine.threadIndex()});
}
// Access to null object is considered always true
return true;
}
final List<Sid> sids =
sidRetrievalStrategy.getSids(SecurityContextHolder.getContext().getAuthentication());
final ObjectIdentity oid =
objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
try {
final Acl acl = aclService.readAclById(oid, sids);
if (acl.isGranted(permissions, sids, false)) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checked authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\". Access is GRANTED.",
new Object[] {TemplateEngine.threadIndex(), authentication.getName(),
domainObject.getClass().getName(), permissions});
}
return true;
}
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checked authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\". Access is DENIED.",
new Object[] {TemplateEngine.threadIndex(), authentication.getName(),
domainObject.getClass().getName(), permissions});
}
return false;
} catch (final NotFoundException nfe) {
return false;
}
}
public static List<Permission> parsePermissionsString(
final ApplicationContext applicationContext, final String permissionsString)
throws NumberFormatException {<FILL_FUNCTION_BODY>}
private static <T> T getBeanOfType(final ApplicationContext applicationContext, final Class<T> type) {
final Map<String, T> map = applicationContext.getBeansOfType(type);
for (ApplicationContext context = applicationContext.getParent(); context != null; context = context.getParent()) {
map.putAll(context.getBeansOfType(type));
}
if (map.size() == 0) {
return null;
} else if (map.size() == 1) {
return map.values().iterator().next();
}
throw new ConfigurationException(
"Found incorrect number of " + type.getSimpleName() +" instances in " +
"application context - you must have only have one!");
}
}
|
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Parsing permissions string \"{}\".",
new Object[] {TemplateEngine.threadIndex(), permissionsString});
}
if (permissionsString == null || permissionsString.trim().length() == 0) {
return Collections.emptyList();
}
PermissionFactory permissionFactory = getBeanOfType(applicationContext, PermissionFactory.class);
if (permissionFactory == null) {
permissionFactory = new DefaultPermissionFactory();
}
final Set<Permission> permissions = new HashSet<Permission>();
final StringTokenizer tokenizer = new StringTokenizer(permissionsString, ",", false);
while (tokenizer.hasMoreTokens()) {
String permission = tokenizer.nextToken();
try {
permissions.add(permissionFactory.buildFromMask(Integer.valueOf(permission).intValue()));
} catch (final NumberFormatException nfe) {
// Not an integer mask. Try using a name
permissions.add(permissionFactory.buildFromName(permission));
}
}
return new ArrayList<Permission>(permissions);
| 1,410
| 293
| 1,703
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/auth/AclAuthorization.java
|
AclAuthorization
|
acl
|
class AclAuthorization {
private final IExpressionContext context;
private final Authentication authentication;
public AclAuthorization(
final IExpressionContext context,
final Authentication authentication) {
super();
this.context = context;
this.authentication = authentication;
}
public Authentication getAuthentication() {
return this.authentication;
}
public boolean acl(final Object domainObject, final String permissions) {<FILL_FUNCTION_BODY>}
}
|
Validate.notEmpty(permissions, "permissions cannot be null or empty");
final ApplicationContext applicationContext = AuthUtils.getContext(this.context);
final List<Permission> permissionsList =
AclAuthUtils.parsePermissionsString(applicationContext, permissions);
return AclAuthUtils.authorizeUsingAccessControlList(
this.context, domainObject, permissionsList, this.authentication);
| 140
| 109
| 249
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/auth/Authorization.java
|
Authorization
|
url
|
class Authorization {
private final IExpressionContext context;
private final Authentication authentication;
public Authorization(
final IExpressionContext context,
final Authentication authentication) {
super();
this.context = context;
this.authentication = authentication;
}
public IExpressionContext getContext() {
return this.context;
}
public Authentication getAuthentication() {
return this.authentication;
}
// Synonym method
public boolean expr(final String expression) {
return expression(expression);
}
public boolean expression(final String expression) {
Validate.notEmpty(expression, "Access expression cannot be null");
return AuthUtils.authorizeUsingAccessExpression(this.context, expression, this.authentication);
}
public boolean url(final String url) {
return url("GET", url);
}
public boolean url(final String method, final String url) {<FILL_FUNCTION_BODY>}
}
|
Validate.notEmpty(url, "URL cannot be null");
return AuthUtils.authorizeUsingUrlCheck(this.context, url, method, this.authentication);
| 282
| 50
| 332
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/SpringSecurityDialect.java
|
SpringSecurityDialect
|
getProcessors
|
class SpringSecurityDialect
extends AbstractDialect
implements IProcessorDialect, IExpressionObjectDialect, IExecutionAttributeDialect {
public static final String NAME = "SpringSecurity";
public static final String DEFAULT_PREFIX = "sec";
public static final int PROCESSOR_PRECEDENCE = 800;
private static final IExpressionObjectFactory EXPRESSION_OBJECT_FACTORY = new SpringSecurityExpressionObjectFactory();
private static final Map<String,Object> EXECUTION_ATTRIBUTES;
// These execution attributes will force the asynchronous resolution of the SecurityContext and the CsrfToken. This
// will avoid the need to block in order to obtain any of them during SpringSecurity-enabled execution. This will
// also mean both objects will be always resolved for every template execution even if not needed, but there is
// no way Thymeleaf could know beforehand if they will be needed for a template or not, so any alternative to this
// would involve blocking.
// NOTE here we are not using the constant from the ReactiveThymeleafView class (instead we replicate its same
// value "ThymeleafReactiveModelAdditions:" so that we don't create a hard dependency on the thymeleaf-spring5
// package, so that this class could be used in the future with, for example, a
// thymeleaf-spring5 integration package if needed.
private static final String SECURITY_CONTEXT_EXECUTION_ATTRIBUTE_NAME =
"ThymeleafReactiveModelAdditions:" + SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME;
private static final String CSRF_EXECUTION_ATTRIBUTE_NAME =
"ThymeleafReactiveModelAdditions:" + CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME;
static {
if (!SpringVersionUtils.isSpringWebFluxPresent()) {
EXECUTION_ATTRIBUTES = null;
} else {
// Returns Mono<SecurityContext>, but we will specify Object in order not to bind this class to Mono at compile time
final Function<ServerWebExchange, Object> secCtxInitializer =
(exchange) -> ReactiveSecurityContextHolder.getContext();
// Returns Mono<SecurityContext>, but we will specify Object in order not to bind this class to Mono at compile time
final Function<ServerWebExchange, Object> csrfTokenInitializer =
(exchange) -> {
final Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName());
if (csrfToken == null) {
return Mono.empty();
}
// We need to put it into the exchange attributes manually here because async resolution
// will only set the result into the MODEL, but RequestDataValueProcessor is expecing this
// specifically as an exchange attribute instead of looking into the model or context.
return csrfToken.doOnSuccess(
token -> exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token));
};
EXECUTION_ATTRIBUTES = new HashMap<>(3, 1.0f);
EXECUTION_ATTRIBUTES.put(SECURITY_CONTEXT_EXECUTION_ATTRIBUTE_NAME, secCtxInitializer);
EXECUTION_ATTRIBUTES.put(CSRF_EXECUTION_ATTRIBUTE_NAME, csrfTokenInitializer);
}
}
public SpringSecurityDialect() {
super(NAME);
}
public String getPrefix() {
return DEFAULT_PREFIX;
}
public int getDialectProcessorPrecedence() {
return PROCESSOR_PRECEDENCE;
}
public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>}
public IExpressionObjectFactory getExpressionObjectFactory() {
return EXPRESSION_OBJECT_FACTORY;
}
@Override
public Map<String, Object> getExecutionAttributes() {
return EXECUTION_ATTRIBUTES;
}
}
|
final Set<IProcessor> processors = new LinkedHashSet<IProcessor>();
final TemplateMode[] templateModes =
new TemplateMode[] {
TemplateMode.HTML, TemplateMode.XML,
TemplateMode.TEXT, TemplateMode.JAVASCRIPT, TemplateMode.CSS };
for (final TemplateMode templateMode : templateModes) {
processors.add(new AuthenticationAttrProcessor(templateMode, dialectPrefix));
// synonym (sec:authorize = sec:authorize-expr) for similarity with
// "authorize-url" and "autorize-acl"
processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME));
processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME_EXPR));
processors.add(new AuthorizeUrlAttrProcessor(templateMode, dialectPrefix));
processors.add(new AuthorizeAclAttrProcessor(templateMode, dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(templateMode, dialectPrefix));
}
return processors;
| 1,078
| 283
| 1,361
|
<methods>public final java.lang.String getName() <variables>private final non-sealed java.lang.String name
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/expression/SpringSecurityExpressionObjectFactory.java
|
SpringSecurityExpressionObjectFactory
|
buildObject
|
class SpringSecurityExpressionObjectFactory implements IExpressionObjectFactory {
/*
* Any new objects added here should also be added to the "ALL_EXPRESSION_OBJECT_NAMES" See below.
*/
public static final String AUTHENTICATION_EXPRESSION_OBJECT_NAME = "authentication";
public static final String AUTHORIZATION_EXPRESSION_OBJECT_NAME = "authorization";
protected static final Set<String> ALL_EXPRESSION_OBJECT_NAMES =
Collections.unmodifiableSet(new LinkedHashSet<String>(java.util.Arrays.asList(
new String[]{
AUTHENTICATION_EXPRESSION_OBJECT_NAME,
AUTHORIZATION_EXPRESSION_OBJECT_NAME
}
)));
public SpringSecurityExpressionObjectFactory() {
super();
}
public Set<String> getAllExpressionObjectNames() {
return ALL_EXPRESSION_OBJECT_NAMES;
}
public boolean isCacheable(final String expressionObjectName) {
// All expression objects created by this factory are cacheable (template-scope)
return true;
}
public Object buildObject(final IExpressionContext context, final String expressionObjectName) {<FILL_FUNCTION_BODY>}
}
|
if (AUTHENTICATION_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (SpringVersionSpecificUtils.isWebContext(context)) {
return AuthUtils.getAuthenticationObject(context);
}
}
if (AUTHORIZATION_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (SpringVersionSpecificUtils.isWebContext(context)) {
// We retrieve it like this in order to give it the opportunity to come from cache
final Authentication authentication =
(Authentication) context.getExpressionObjects().getObject(AUTHENTICATION_EXPRESSION_OBJECT_NAME);
return new Authorization(context, authentication);
}
return null;
}
return null;
| 338
| 196
| 534
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/processor/AuthenticationAttrProcessor.java
|
AuthenticationAttrProcessor
|
doProcess
|
class AuthenticationAttrProcessor extends AbstractAttributeTagProcessor {
public static final int ATTR_PRECEDENCE = 1300;
public static final String ATTR_NAME = "authentication";
public AuthenticationAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, ATTR_PRECEDENCE, true);
}
@Override
protected void doProcess(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
final Object authenticationProperty = AuthUtils.getAuthenticationProperty(authentication, attrValue);
if (authenticationProperty == null) {
return;
}
String encodedAttribute = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), authenticationProperty.toString());
structureHandler.setBody(encodedAttribute, false);
| 183
| 146
| 329
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/processor/AuthorizeAclAttrProcessor.java
|
AuthorizeAclAttrProcessor
|
getExpressionDefaultToLiteral
|
class AuthorizeAclAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize-acl";
private static final String VALUE_SEPARATOR = "::";
public AuthorizeAclAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
final ApplicationContext applicationContext = AuthUtils.getContext(context);
final IEngineConfiguration configuration = context.getConfiguration();
final int separatorPos = attrValue.lastIndexOf(VALUE_SEPARATOR);
if (separatorPos == -1) {
throw new TemplateProcessingException(
"Could not parse \"" + attributeValue + "\" as an access control list " +
"expression. Syntax should be \"[domain object expression] :: [permissions]\"");
}
final String domainObjectExpression = attrValue.substring(0,separatorPos).trim();
final String permissionsExpression = attrValue.substring(separatorPos + 2).trim();
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression domainObjectExpr =
getExpressionDefaultToLiteral(expressionParser, context, domainObjectExpression);
final IStandardExpression permissionsExpr =
getExpressionDefaultToLiteral(expressionParser, context, permissionsExpression);
final Object domainObject = domainObjectExpr.execute(context);
final Object permissionsObject = permissionsExpr.execute(context);
final String permissionsStr =
(permissionsObject == null? null : permissionsObject.toString());
return AclAuthUtils.authorizeUsingAccessControlList(
context, domainObject, applicationContext, permissionsStr, authentication);
}
protected static IStandardExpression getExpressionDefaultToLiteral(
final IStandardExpressionParser expressionParser, final IExpressionContext context, final String input) {<FILL_FUNCTION_BODY>}
}
|
final IStandardExpression expression = expressionParser.parseExpression(context, input);
if (expression == null) {
return new TextLiteralExpression(input);
}
return expression;
| 638
| 50
| 688
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/processor/AuthorizeAttrProcessor.java
|
AuthorizeAttrProcessor
|
isVisible
|
class AuthorizeAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize";
public static final String ATTR_NAME_EXPR = "authorize-expr";
public AuthorizeAttrProcessor(final TemplateMode templateMode, final String dialectPrefix, final String attrName) {
super(templateMode, dialectPrefix, attrName, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
return AuthUtils.authorizeUsingAccessExpression(context, attrValue, authentication);
| 192
| 108
| 300
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/dialect/processor/AuthorizeUrlAttrProcessor.java
|
AuthorizeUrlAttrProcessor
|
isVisible
|
class AuthorizeUrlAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize-url";
public AuthorizeUrlAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final int spaceIndex = attrValue.indexOf(' ');
final String url =
(spaceIndex < 0? attrValue : attrValue.substring(spaceIndex + 1)).trim();
final String method =
(spaceIndex < 0? "GET" : attrValue.substring(0, spaceIndex)).trim();
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
return AuthUtils.authorizeUsingUrlCheck(context, url, method, authentication);
| 174
| 185
| 359
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/util/Spring5VersionSpecificUtility.java
|
Spring5VersionSpecificUtility
|
getServletWebExchange
|
class Spring5VersionSpecificUtility implements ISpringVersionSpecificUtility {
Spring5VersionSpecificUtility() {
super();
}
public EvaluationContext wrapEvaluationContext(
final EvaluationContext evaluationContext, final IExpressionObjects expresionObjects) {
final IThymeleafEvaluationContext thymeleafEvaluationContext = new ThymeleafEvaluationContextWrapper(evaluationContext);
thymeleafEvaluationContext.setExpressionObjects(expresionObjects);
return thymeleafEvaluationContext;
}
@Override
public boolean isWebContext(final IContext context) {
if (context instanceof IWebContext) {
return true;
}
return false;
}
@Override
public boolean isWebMvcContext(final IContext context) {
if (context instanceof IWebContext) {
IWebContext webContext = (IWebContext) context;
IWebExchange webExchange = webContext.getExchange();
if (webExchange instanceof IServletWebExchange) {
return true;
}
}
return false;
}
@Override
public boolean isWebFluxContext(final IContext context) {
if (!isWebContext(context)) {
return false;
}
return getWebExchange(context) instanceof ISpringWebFluxWebExchange;
}
@Override
public HttpServletRequest getHttpServletRequest(final IContext context) {
return (HttpServletRequest) getServletWebExchange(context).getNativeRequestObject();
}
@Override
public HttpServletResponse getHttpServletResponse(final IContext context) {
return (HttpServletResponse) getServletWebExchange(context).getNativeResponseObject();
}
@Override
public ServerWebExchange getServerWebExchange(final IContext context) {
IWebExchange webExchange = getWebExchange(context);
if (webExchange instanceof ISpringWebFluxWebExchange) {
ISpringWebFluxWebExchange webFluxWebExchange = (ISpringWebFluxWebExchange) webExchange;
return (ServerWebExchange) webFluxWebExchange.getNativeExchangeObject();
}
throw new TemplateProcessingException(
"Cannot obtain ServerWebExchange from a non-WebFlux context implementation (\"" +
context.getClass().getName() + "\")");
}
private static IServletWebExchange getServletWebExchange(final IContext context) {<FILL_FUNCTION_BODY>}
private static IWebExchange getWebExchange(final IContext context) {
if (context instanceof IWebContext) {
IWebContext webContext = (IWebContext) context;
return webContext.getExchange();
}
throw new TemplateProcessingException(
"Cannot obtain IWebExchange from a non-Servlet context implementation (\"" +
context.getClass().getName() + "\")");
}
}
|
IWebExchange webExchange = getWebExchange(context);
if (webExchange instanceof IServletWebExchange) {
return (IServletWebExchange) webExchange;
}
throw new TemplateProcessingException(
"Cannot obtain IServletWebExchange from a non-Servlet context implementation (\"" +
context.getClass().getName() + "\")");
| 771
| 97
| 868
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/util/SpringSecurityVersionUtils.java
|
SpringSecurityVersionUtils
|
testClassExistence
|
class SpringSecurityVersionUtils {
private static final int SPRING_SECURITY_VERSION_MAJOR;
private static final int SPRING_SECURITY_VERSION_MINOR;
static {
String springSecurityVersion = SpringSecurityCoreVersion.getVersion();
// We will first compute the package name root for the spring framework in order to improve resilience
// against dependency renaming operations.
final String securityCorePackageName = SpringSecurityCoreVersion.class.getPackage().getName();
final String springSecurityPackageName =
securityCorePackageName.substring(0, securityCorePackageName.length() - 5); // - ".core"
// There might be times when SpringVersion cannot determine the version due to CL restrictions (see doc)
if (springSecurityVersion != null) {
try {
String versionRemainder = springSecurityVersion;
int separatorIdx = versionRemainder.indexOf('.');
SPRING_SECURITY_VERSION_MAJOR = Integer.parseInt(versionRemainder.substring(0, separatorIdx));
int separator2Idx = versionRemainder.indexOf('.', separatorIdx + 1);
SPRING_SECURITY_VERSION_MINOR = Integer.parseInt(versionRemainder.substring(separatorIdx + 1, separator2Idx));
} catch (final Exception e) {
throw new ExceptionInInitializerError(
"Exception during initialization of Spring Security versioning utilities. Identified Spring Security " +
"version is '" + springSecurityVersion + "', which does not follow the {major}.{minor}.{...} scheme");
}
} else {
if (testClassExistence(springSecurityPackageName + ".web.server.context.SecurityContextServerWebExchange")) {
SPRING_SECURITY_VERSION_MAJOR = 5;
SPRING_SECURITY_VERSION_MINOR = 0;
} else if (testClassExistence(springSecurityPackageName + ".jackson2.SecurityJackson2Modules")) {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 2;
} else if (testClassExistence(springSecurityPackageName + ".core.annotation.AuthenticationPrincipal")) {
// There are no new classes at the core of Spring Security 4.1, so we will check for a new
// "expression()" attribute method in the AuthenticationPrincipal annotation, which was added in 4.0
final Class<?> authenticationPrincipalClass =
getClass(springSecurityPackageName + ".core.annotation.AuthenticationPrincipal");
final Method[] methods = authenticationPrincipalClass.getDeclaredMethods();
boolean hasExpressionAttribute = false;
for (int i = 0; i < methods.length; i++) {
if ("expression".equals(methods[i].getName())) {
hasExpressionAttribute = true;
}
}
if (hasExpressionAttribute) {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 1;
} else {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 0;
}
} else if (testClassExistence(springSecurityPackageName + ".access.method.P")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 2;
} else if (testClassExistence(springSecurityPackageName + ".provisioning.MutableUserDetails")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 1;
} else if (testClassExistence(springSecurityPackageName + ".access.expression.method.AbstractExpressionBasedMethodConfigAttribute")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 0;
} else {
// We will default to 2.0
SPRING_SECURITY_VERSION_MAJOR = 2;
SPRING_SECURITY_VERSION_MINOR = 0;
}
}
}
private static boolean testClassExistence(final String className) {<FILL_FUNCTION_BODY>}
private static Class<?> getClass(final String className) {
final ClassLoader classLoader = ClassLoaderUtils.getClassLoader(SpringSecurityVersionUtils.class);
try {
return Class.forName(className, false, classLoader);
} catch (final Throwable t) {
return null;
}
}
public static int getSpringSecurityVersionMajor() {
return SPRING_SECURITY_VERSION_MAJOR;
}
public static int getSpringSecurityVersionMinor() {
return SPRING_SECURITY_VERSION_MINOR;
}
public static boolean isSpringSecurity30AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 3;
}
public static boolean isSpringSecurity31AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 3 || (SPRING_SECURITY_VERSION_MAJOR == 3 && SPRING_SECURITY_VERSION_MINOR >= 1);
}
public static boolean isSpringSecurity32AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 3 || (SPRING_SECURITY_VERSION_MAJOR == 3 && SPRING_SECURITY_VERSION_MINOR >= 2);
}
public static boolean isSpringSecurity40AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 4;
}
public static boolean isSpringSecurity41AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 4 || (SPRING_SECURITY_VERSION_MAJOR == 4 && SPRING_SECURITY_VERSION_MINOR >= 1);
}
public static boolean isSpringSecurity42AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 4 || (SPRING_SECURITY_VERSION_MAJOR == 4 && SPRING_SECURITY_VERSION_MINOR >= 2);
}
public static boolean isSpringSecurity50AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 5;
}
private SpringSecurityVersionUtils() {
super();
}
}
|
final ClassLoader classLoader = ClassLoaderUtils.getClassLoader(SpringSecurityVersionUtils.class);
try {
Class.forName(className, false, classLoader);
return true;
} catch (final Throwable t) {
return false;
}
| 1,680
| 70
| 1,750
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity5/src/main/java/org/thymeleaf/extras/springsecurity5/util/SpringVersionSpecificUtils.java
|
SpringVersionSpecificUtils
|
wrapEvaluationContext
|
class SpringVersionSpecificUtils {
private static final Logger LOG = LoggerFactory.getLogger(SpringVersionSpecificUtils.class);
private static final String PACKAGE_NAME = SpringVersionSpecificUtils.class.getPackage().getName();
// Spring Security 5 requires at least Spring 5
private static final String SPRING5_DELEGATE_CLASS = PACKAGE_NAME + ".Spring5VersionSpecificUtility";
private static final ISpringVersionSpecificUtility spring5Delegate;
static {
if (SpringVersionUtils.isSpring50AtLeast() && ! SpringVersionUtils.isSpring60AtLeast()) {
LOG.trace("[THYMELEAF][TESTING] Spring 5.x+ found on classpath. Initializing version-specific utilities for Spring 5");
try {
final Class<?> implClass = ClassLoaderUtils.loadClass(SPRING5_DELEGATE_CLASS);
spring5Delegate = (ISpringVersionSpecificUtility) implClass.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
throw new ExceptionInInitializerError(
new ConfigurationException(
"Environment has been detected to be at least Spring 5, but thymeleaf could not initialize a " +
"delegate of class \"" + SPRING5_DELEGATE_CLASS + "\"", e));
}
} else {
throw new ExceptionInInitializerError(
new ConfigurationException(
"The Spring-version-specific infrastructure could not create utility for the specific " +
"version of Spring being used. Currently only Spring 5.x is supported."));
}
}
public static EvaluationContext wrapEvaluationContext(
final EvaluationContext evaluationContext, final IExpressionObjects expresionObjects) {<FILL_FUNCTION_BODY>}
public static boolean isWebContext(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.isWebContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x is supported.");
}
public static boolean isWebMvcContext(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.isWebMvcContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x is supported.");
}
public static boolean isWebFluxContext(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.isWebFluxContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x is supported.");
}
public static HttpServletRequest getHttpServletRequest(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.getHttpServletRequest(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x or newer is supported.");
}
public static HttpServletResponse getHttpServletResponse(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.getHttpServletResponse(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x or newer is supported.");
}
public static ServerWebExchange getServerWebExchange(final IContext context) {
if (spring5Delegate != null) {
return spring5Delegate.getServerWebExchange(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x or newer is supported.");
}
private SpringVersionSpecificUtils() {
super();
}
}
|
if (spring5Delegate != null) {
return spring5Delegate.wrapEvaluationContext(evaluationContext, expresionObjects);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 5.x is supported.");
| 1,100
| 85
| 1,185
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/auth/AclAuthUtils.java
|
AclAuthUtils
|
getBeanOfType
|
class AclAuthUtils {
private static final Logger logger = LoggerFactory.getLogger(AclAuthUtils.class);
private AclAuthUtils() {
super();
}
public static boolean authorizeUsingAccessControlList(
final IExpressionContext context,
final Object domainObject,
final ApplicationContext applicationContext, final String permissionsString,
final Authentication authentication) {
final List<Permission> permissions =
parsePermissionsString(applicationContext, permissionsString);
return authorizeUsingAccessControlList(context, domainObject, permissions, authentication);
}
public static boolean authorizeUsingAccessControlList(
final IExpressionContext context,
final Object domainObject, final List<Permission> permissions,
final Authentication authentication) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checking authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\".",
new Object[] {TemplateEngine.threadIndex(), (authentication == null? null : authentication.getName()),
(domainObject == null? null : domainObject.getClass().getName()), permissions});
}
final ApplicationContext applicationContext = AuthUtils.getContext(context);
final AclService aclService = getBeanOfType(applicationContext, AclService.class);
if (authentication == null) {
// If authentication is null, authorization cannot be granted.
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Authentication object is null. Access is DENIED. ",
new Object[] {TemplateEngine.threadIndex()});
}
return false;
}
/*
* Initialize required objects
*/
SidRetrievalStrategy sidRetrievalStrategy = getBeanOfType(applicationContext, SidRetrievalStrategy.class);
if (sidRetrievalStrategy == null) {
sidRetrievalStrategy = new SidRetrievalStrategyImpl();
}
ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = getBeanOfType(applicationContext, ObjectIdentityRetrievalStrategy.class);
if (objectIdentityRetrievalStrategy == null) {
objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
}
/*
* Compute permissions
*/
if ((null == permissions) || permissions.isEmpty()) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Permissions are null or empty. Access is DENIED. ",
new Object[] {TemplateEngine.threadIndex()});
}
return false;
}
if (domainObject == null) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Domain object for resolved to null. Access by " +
"Access Control List is GRANTED.", new Object[] {TemplateEngine.threadIndex()});
}
// Access to null object is considered always true
return true;
}
final List<Sid> sids =
sidRetrievalStrategy.getSids(SecurityContextHolder.getContext().getAuthentication());
final ObjectIdentity oid =
objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
try {
final Acl acl = aclService.readAclById(oid, sids);
if (acl.isGranted(permissions, sids, false)) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checked authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\". Access is GRANTED.",
new Object[] {TemplateEngine.threadIndex(), authentication.getName(),
domainObject.getClass().getName(), permissions});
}
return true;
}
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Checked authorization using Access Control List for user \"{}\". " +
"Domain object is of class \"{}\" and permissions are \"{}\". Access is DENIED.",
new Object[] {TemplateEngine.threadIndex(), authentication.getName(),
domainObject.getClass().getName(), permissions});
}
return false;
} catch (final NotFoundException nfe) {
return false;
}
}
public static List<Permission> parsePermissionsString(
final ApplicationContext applicationContext, final String permissionsString)
throws NumberFormatException {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Parsing permissions string \"{}\".",
new Object[] {TemplateEngine.threadIndex(), permissionsString});
}
if (permissionsString == null || permissionsString.trim().length() == 0) {
return Collections.emptyList();
}
PermissionFactory permissionFactory = getBeanOfType(applicationContext, PermissionFactory.class);
if (permissionFactory == null) {
permissionFactory = new DefaultPermissionFactory();
}
final Set<Permission> permissions = new HashSet<Permission>();
final StringTokenizer tokenizer = new StringTokenizer(permissionsString, ",", false);
while (tokenizer.hasMoreTokens()) {
String permission = tokenizer.nextToken();
try {
permissions.add(permissionFactory.buildFromMask(Integer.valueOf(permission).intValue()));
} catch (final NumberFormatException nfe) {
// Not an integer mask. Try using a name
permissions.add(permissionFactory.buildFromName(permission));
}
}
return new ArrayList<Permission>(permissions);
}
private static <T> T getBeanOfType(final ApplicationContext applicationContext, final Class<T> type) {<FILL_FUNCTION_BODY>}
}
|
final Map<String, T> map = applicationContext.getBeansOfType(type);
for (ApplicationContext context = applicationContext.getParent(); context != null; context = context.getParent()) {
map.putAll(context.getBeansOfType(type));
}
if (map.size() == 0) {
return null;
} else if (map.size() == 1) {
return map.values().iterator().next();
}
throw new ConfigurationException(
"Found incorrect number of " + type.getSimpleName() +" instances in " +
"application context - you must have only have one!");
| 1,505
| 164
| 1,669
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/auth/AclAuthorization.java
|
AclAuthorization
|
acl
|
class AclAuthorization {
private final IExpressionContext context;
private final Authentication authentication;
public AclAuthorization(
final IExpressionContext context,
final Authentication authentication) {
super();
this.context = context;
this.authentication = authentication;
}
public Authentication getAuthentication() {
return this.authentication;
}
public boolean acl(final Object domainObject, final String permissions) {<FILL_FUNCTION_BODY>}
}
|
Validate.notEmpty(permissions, "permissions cannot be null or empty");
final ApplicationContext applicationContext = AuthUtils.getContext(this.context);
final List<Permission> permissionsList =
AclAuthUtils.parsePermissionsString(applicationContext, permissions);
return AclAuthUtils.authorizeUsingAccessControlList(
this.context, domainObject, permissionsList, this.authentication);
| 138
| 105
| 243
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/auth/AuthUtils.java
|
MinimalAuthenticationExpressionSupport
|
evaluateMinimalExpression
|
class MinimalAuthenticationExpressionSupport {
// -----------------------------------------------------------------------------------------------
// This class is meant to given a minimal support to Spring Security expressions available at
// the sec:authorize tags for Spring WebFlux applications, for which Spring Security (as of 5.1)
// does not provide full support for expression execution.
// -----------------------------------------------------------------------------------------------
// Fixing the impl doesn't seem completely right, but actually it's what is currently being done at
// Spring Security's "DefaultWebSecurityExpressionHandler" (as of Spring Security 5.1)
private static final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
// We will define "minimal support" as only supporting these specific expressions, which only
// require involvement of the trust resolver.
private static final String EXPR_ISAUTHENTICATED = "isAuthenticated()";
private static final String EXPR_ISFULLYAUTHENTICATED = "isFullyAuthenticated()";
private static final String EXPR_ISANONYMOUS = "isAnonymous()";
private static final String EXPR_ISREMEMBERME = "isRememberMe()";
private static final Set<String> HANDLED_EXPRESSIONS =
new LinkedHashSet<String>(Arrays.asList(new String[] {
EXPR_ISAUTHENTICATED, EXPR_ISFULLYAUTHENTICATED, EXPR_ISANONYMOUS, EXPR_ISREMEMBERME
}));
static boolean isMinimalHandledExpression(final String accessExpression) {
return HANDLED_EXPRESSIONS.contains(accessExpression);
}
static boolean evaluateMinimalExpression(final String accessExpression, final Authentication authentication) {<FILL_FUNCTION_BODY>}
private static boolean isAnonymous(final Authentication authentication) {
return trustResolver.isAnonymous(authentication);
}
private static boolean isAuthenticated(final Authentication authentication) {
return !isAnonymous(authentication);
}
private static boolean isRememberMe(final Authentication authentication) {
return trustResolver.isRememberMe(authentication);
}
private static boolean isFullyAuthenticated(final Authentication authentication) {
return !trustResolver.isAnonymous(authentication)
&& !trustResolver.isRememberMe(authentication);
}
}
|
if (EXPR_ISAUTHENTICATED.equals(accessExpression)) {
return isAuthenticated(authentication);
}
if (EXPR_ISFULLYAUTHENTICATED.equals(accessExpression)) {
return isFullyAuthenticated(authentication);
}
if (EXPR_ISANONYMOUS.equals(accessExpression)) {
return isAnonymous(authentication);
}
if (EXPR_ISREMEMBERME.equals(accessExpression)) {
return isRememberMe(authentication);
}
throw new IllegalArgumentException(
"Unknown minimal expression: \"" + accessExpression + "\". Supported expressions are: " +
HANDLED_EXPRESSIONS);
| 587
| 181
| 768
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/auth/Authorization.java
|
Authorization
|
url
|
class Authorization {
private final IExpressionContext context;
private final Authentication authentication;
public Authorization(
final IExpressionContext context,
final Authentication authentication) {
super();
this.context = context;
this.authentication = authentication;
}
public IExpressionContext getContext() {
return this.context;
}
public Authentication getAuthentication() {
return this.authentication;
}
// Synonym method
public boolean expr(final String expression) {
return expression(expression);
}
public boolean expression(final String expression) {
Validate.notEmpty(expression, "Access expression cannot be null");
return AuthUtils.authorizeUsingAccessExpression(this.context, expression, this.authentication);
}
public boolean url(final String url) {
return url("GET", url);
}
public boolean url(final String method, final String url) {<FILL_FUNCTION_BODY>}
}
|
Validate.notEmpty(url, "URL cannot be null");
return AuthUtils.authorizeUsingUrlCheck(this.context, url, method, this.authentication);
| 271
| 47
| 318
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/SpringSecurityDialect.java
|
SpringSecurityDialect
|
getProcessors
|
class SpringSecurityDialect
extends AbstractDialect
implements IProcessorDialect, IExpressionObjectDialect, IExecutionAttributeDialect {
public static final String NAME = "SpringSecurity";
public static final String DEFAULT_PREFIX = "sec";
public static final int PROCESSOR_PRECEDENCE = 800;
private static final IExpressionObjectFactory EXPRESSION_OBJECT_FACTORY = new SpringSecurityExpressionObjectFactory();
private static final Map<String,Object> EXECUTION_ATTRIBUTES;
// These execution attributes will force the asynchronous resolution of the SecurityContext and the CsrfToken. This
// will avoid the need to block in order to obtain any of them during SpringSecurity-enabled execution. This will
// also mean both objects will be always resolved for every template execution even if not needed, but there is
// no way Thymeleaf could know beforehand if they will be needed for a template or not, so any alternative to this
// would involve blocking.
// NOTE here we are not using the constant from the ReactiveThymeleafView class (instead we replicate its same
// value "ThymeleafReactiveModelAdditions:" so that we don't create a hard dependency on the thymeleaf-spring6
// package, so that this class could be used in the future with, for example, a
// thymeleaf-spring6 integration package if needed.
private static final String SECURITY_CONTEXT_EXECUTION_ATTRIBUTE_NAME =
"ThymeleafReactiveModelAdditions:" + SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME;
private static final String CSRF_EXECUTION_ATTRIBUTE_NAME =
"ThymeleafReactiveModelAdditions:" + CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME;
static {
if (!SpringVersionUtils.isSpringWebFluxPresent()) {
EXECUTION_ATTRIBUTES = null;
} else {
// Returns Mono<SecurityContext>, but we will specify Object in order not to bind this class to Mono at compile time
final Function<ServerWebExchange, Object> secCtxInitializer =
(exchange) -> ReactiveSecurityContextHolder.getContext();
// Returns Mono<SecurityContext>, but we will specify Object in order not to bind this class to Mono at compile time
final Function<ServerWebExchange, Object> csrfTokenInitializer =
(exchange) -> {
final Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName());
if (csrfToken == null) {
return Mono.empty();
}
// We need to put it into the exchange attributes manually here because async resolution
// will only set the result into the MODEL, but RequestDataValueProcessor is expecing this
// specifically as an exchange attribute instead of looking into the model or context.
return csrfToken.doOnSuccess(
token -> exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token));
};
EXECUTION_ATTRIBUTES = new HashMap<>(3, 1.0f);
EXECUTION_ATTRIBUTES.put(SECURITY_CONTEXT_EXECUTION_ATTRIBUTE_NAME, secCtxInitializer);
EXECUTION_ATTRIBUTES.put(CSRF_EXECUTION_ATTRIBUTE_NAME, csrfTokenInitializer);
}
}
public SpringSecurityDialect() {
super(NAME);
}
public String getPrefix() {
return DEFAULT_PREFIX;
}
public int getDialectProcessorPrecedence() {
return PROCESSOR_PRECEDENCE;
}
public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>}
public IExpressionObjectFactory getExpressionObjectFactory() {
return EXPRESSION_OBJECT_FACTORY;
}
@Override
public Map<String, Object> getExecutionAttributes() {
return EXECUTION_ATTRIBUTES;
}
}
|
final Set<IProcessor> processors = new LinkedHashSet<IProcessor>();
final TemplateMode[] templateModes =
new TemplateMode[] {
TemplateMode.HTML, TemplateMode.XML,
TemplateMode.TEXT, TemplateMode.JAVASCRIPT, TemplateMode.CSS };
for (final TemplateMode templateMode : templateModes) {
processors.add(new AuthenticationAttrProcessor(templateMode, dialectPrefix));
// synonym (sec:authorize = sec:authorize-expr) for similarity with
// "authorize-url" and "autorize-acl"
processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME));
processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME_EXPR));
processors.add(new AuthorizeUrlAttrProcessor(templateMode, dialectPrefix));
processors.add(new AuthorizeAclAttrProcessor(templateMode, dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(templateMode, dialectPrefix));
}
return processors;
| 1,075
| 283
| 1,358
|
<methods>public final java.lang.String getName() <variables>private final non-sealed java.lang.String name
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/expression/SpringSecurityExpressionObjectFactory.java
|
SpringSecurityExpressionObjectFactory
|
buildObject
|
class SpringSecurityExpressionObjectFactory implements IExpressionObjectFactory {
/*
* Any new objects added here should also be added to the "ALL_EXPRESSION_OBJECT_NAMES" See below.
*/
public static final String AUTHENTICATION_EXPRESSION_OBJECT_NAME = "authentication";
public static final String AUTHORIZATION_EXPRESSION_OBJECT_NAME = "authorization";
protected static final Set<String> ALL_EXPRESSION_OBJECT_NAMES =
Collections.unmodifiableSet(new LinkedHashSet<String>(java.util.Arrays.asList(
new String[]{
AUTHENTICATION_EXPRESSION_OBJECT_NAME,
AUTHORIZATION_EXPRESSION_OBJECT_NAME
}
)));
public SpringSecurityExpressionObjectFactory() {
super();
}
public Set<String> getAllExpressionObjectNames() {
return ALL_EXPRESSION_OBJECT_NAMES;
}
public boolean isCacheable(final String expressionObjectName) {
// All expression objects created by this factory are cacheable (template-scope)
return true;
}
public Object buildObject(final IExpressionContext context, final String expressionObjectName) {<FILL_FUNCTION_BODY>}
}
|
if (AUTHENTICATION_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (SpringVersionSpecificUtils.isWebContext(context)) {
return AuthUtils.getAuthenticationObject(context);
}
}
if (AUTHORIZATION_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (SpringVersionSpecificUtils.isWebContext(context)) {
// We retrieve it like this in order to give it the opportunity to come from cache
final Authentication authentication =
(Authentication) context.getExpressionObjects().getObject(AUTHENTICATION_EXPRESSION_OBJECT_NAME);
return new Authorization(context, authentication);
}
return null;
}
return null;
| 338
| 196
| 534
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/processor/AuthenticationAttrProcessor.java
|
AuthenticationAttrProcessor
|
doProcess
|
class AuthenticationAttrProcessor extends AbstractAttributeTagProcessor {
public static final int ATTR_PRECEDENCE = 1300;
public static final String ATTR_NAME = "authentication";
public AuthenticationAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, ATTR_PRECEDENCE, true);
}
@Override
protected void doProcess(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
final Object authenticationProperty = AuthUtils.getAuthenticationProperty(authentication, attrValue);
if (authenticationProperty == null) {
return;
}
String encodedAttribute = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), authenticationProperty.toString());
structureHandler.setBody(encodedAttribute, false);
| 181
| 146
| 327
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/processor/AuthorizeAclAttrProcessor.java
|
AuthorizeAclAttrProcessor
|
isVisible
|
class AuthorizeAclAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize-acl";
private static final String VALUE_SEPARATOR = "::";
public AuthorizeAclAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>}
protected static IStandardExpression getExpressionDefaultToLiteral(
final IStandardExpressionParser expressionParser, final IExpressionContext context, final String input) {
final IStandardExpression expression = expressionParser.parseExpression(context, input);
if (expression == null) {
return new TextLiteralExpression(input);
}
return expression;
}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
final ApplicationContext applicationContext = AuthUtils.getContext(context);
final IEngineConfiguration configuration = context.getConfiguration();
final int separatorPos = attrValue.lastIndexOf(VALUE_SEPARATOR);
if (separatorPos == -1) {
throw new TemplateProcessingException(
"Could not parse \"" + attributeValue + "\" as an access control list " +
"expression. Syntax should be \"[domain object expression] :: [permissions]\"");
}
final String domainObjectExpression = attrValue.substring(0,separatorPos).trim();
final String permissionsExpression = attrValue.substring(separatorPos + 2).trim();
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression domainObjectExpr =
getExpressionDefaultToLiteral(expressionParser, context, domainObjectExpression);
final IStandardExpression permissionsExpr =
getExpressionDefaultToLiteral(expressionParser, context, permissionsExpression);
final Object domainObject = domainObjectExpr.execute(context);
final Object permissionsObject = permissionsExpr.execute(context);
final String permissionsStr =
(permissionsObject == null? null : permissionsObject.toString());
return AclAuthUtils.authorizeUsingAccessControlList(
context, domainObject, applicationContext, permissionsStr, authentication);
| 275
| 410
| 685
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/processor/AuthorizeAttrProcessor.java
|
AuthorizeAttrProcessor
|
isVisible
|
class AuthorizeAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize";
public static final String ATTR_NAME_EXPR = "authorize-expr";
public AuthorizeAttrProcessor(final TemplateMode templateMode, final String dialectPrefix, final String attrName) {
super(templateMode, dialectPrefix, attrName, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
return AuthUtils.authorizeUsingAccessExpression(context, attrValue, authentication);
| 189
| 108
| 297
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/dialect/processor/AuthorizeUrlAttrProcessor.java
|
AuthorizeUrlAttrProcessor
|
isVisible
|
class AuthorizeUrlAttrProcessor extends AbstractStandardConditionalVisibilityTagProcessor {
public static final int ATTR_PRECEDENCE = 300;
public static final String ATTR_NAME = "authorize-url";
public AuthorizeUrlAttrProcessor(final TemplateMode templateMode, final String dialectPrefix) {
super(templateMode, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected boolean isVisible(
final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>}
}
|
final String attrValue = (attributeValue == null? null : attributeValue.trim());
if (attrValue == null || attrValue.length() == 0) {
return false;
}
final int spaceIndex = attrValue.indexOf(' ');
final String url =
(spaceIndex < 0? attrValue : attrValue.substring(spaceIndex + 1)).trim();
final String method =
(spaceIndex < 0? "GET" : attrValue.substring(0, spaceIndex)).trim();
final Authentication authentication = AuthUtils.getAuthenticationObject(context);
if (authentication == null) {
return false;
}
return AuthUtils.authorizeUsingUrlCheck(context, url, method, authentication);
| 167
| 185
| 352
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/util/Spring6VersionSpecificUtility.java
|
Spring6VersionSpecificUtility
|
isWebMvcContext
|
class Spring6VersionSpecificUtility implements ISpringVersionSpecificUtility {
Spring6VersionSpecificUtility() {
super();
}
public EvaluationContext wrapEvaluationContext(
final EvaluationContext evaluationContext, final IExpressionObjects expresionObjects) {
final IThymeleafEvaluationContext thymeleafEvaluationContext = new ThymeleafEvaluationContextWrapper(evaluationContext);
thymeleafEvaluationContext.setExpressionObjects(expresionObjects);
return thymeleafEvaluationContext;
}
@Override
public boolean isWebContext(final IContext context) {
if (context instanceof IWebContext) {
return true;
}
return false;
}
@Override
public boolean isWebMvcContext(final IContext context) {<FILL_FUNCTION_BODY>}
@Override
public boolean isWebFluxContext(final IContext context) {
if (!isWebContext(context)) {
return false;
}
return getWebExchange(context) instanceof ISpringWebFluxWebExchange;
}
@Override
public HttpServletRequest getHttpServletRequest(final IContext context) {
return (HttpServletRequest) getServletWebExchange(context).getNativeRequestObject();
}
@Override
public HttpServletResponse getHttpServletResponse(final IContext context) {
return (HttpServletResponse) getServletWebExchange(context).getNativeResponseObject();
}
@Override
public ServerWebExchange getServerWebExchange(final IContext context) {
IWebExchange webExchange = getWebExchange(context);
if (webExchange instanceof ISpringWebFluxWebExchange) {
ISpringWebFluxWebExchange webFluxWebExchange = (ISpringWebFluxWebExchange) webExchange;
return (ServerWebExchange) webFluxWebExchange.getNativeExchangeObject();
}
throw new TemplateProcessingException(
"Cannot obtain ServerWebExchange from a non-WebFlux context implementation (\"" +
context.getClass().getName() + "\")");
}
private static IServletWebExchange getServletWebExchange(final IContext context) {
IWebExchange webExchange = getWebExchange(context);
if (webExchange instanceof IServletWebExchange) {
return (IServletWebExchange) webExchange;
}
throw new TemplateProcessingException(
"Cannot obtain IServletWebExchange from a non-Servlet context implementation (\"" +
context.getClass().getName() + "\")");
}
private static IWebExchange getWebExchange(final IContext context) {
if (context instanceof IWebContext) {
IWebContext webContext = (IWebContext) context;
return webContext.getExchange();
}
throw new TemplateProcessingException(
"Cannot obtain IWebExchange from a non-Servlet context implementation (\"" +
context.getClass().getName() + "\")");
}
}
|
if (context instanceof IWebContext) {
IWebContext webContext = (IWebContext) context;
IWebExchange webExchange = webContext.getExchange();
if (webExchange instanceof IServletWebExchange) {
return true;
}
}
return false;
| 783
| 78
| 861
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/util/SpringSecurityContextUtils.java
|
SpringSecurityWebMvcApplicationContextUtils
|
findRequiredWebApplicationContext
|
class SpringSecurityWebMvcApplicationContextUtils {
static Object getRequestAttribute(final IContext context, final String attributeName) {
return ((IWebContext)context).getExchange().getAttributeValue(attributeName);
}
static String getContextPath(final IContext context) {
WebEngineContext webEngineContext = (WebEngineContext) context;
IWebExchange webExchange = webEngineContext.getExchange();
IServletWebExchange servletWebExchange = (IServletWebExchange) webExchange;
return servletWebExchange.getRequest().getContextPath();
}
/*
* This method mimics the behaviour in
* org.springframework.security.web.context.support.SecurityWebApplicationContextUtils#findRequiredWebApplicationContext(sc),
* which provides a default mechanism for looking for the WebApplicationContext as an attribute of the
* ServletContext that might have been declared with a non-standard name (if it had, it would be
* detected by WebApplicationContextUtils.getWebApplicationContext(sc). This is a behaviour directly
* supported in Spring Framework >= 4.2 thanks to
* org.springframework.web.context.support.WebApplicationContextUtils#findWebApplicationContext(sc).
*
* Unfortunately, the org.springframework.security.web.context.support.SecurityWebApplicationContextUtils class is
* only available since Spring Security 4.1, so we cannot simply call it if we want to support Spring Security 4.0.
* That's why this method basically mimics its behaviour.
*/
static ApplicationContext findRequiredWebApplicationContext(final IContext context) {<FILL_FUNCTION_BODY>}
static Authentication getAuthenticationObject() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext == null) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] No security context found, no authentication object returned.",
new Object[] {TemplateEngine.threadIndex()});
}
return null;
}
return securityContext.getAuthentication();
}
}
|
IServletWebApplication application = (IServletWebApplication) ((IWebContext) context).getExchange().getApplication();
ServletContext servletContext = (ServletContext) application.getNativeServletContextObject();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
if (wac == null) {
final Enumeration<String> attrNames = servletContext.getAttributeNames();
while (attrNames.hasMoreElements()) {
final String attrName = attrNames.nextElement();
final Object attrValue = servletContext.getAttribute(attrName);
if (attrValue instanceof WebApplicationContext) {
if (wac != null) {
throw new IllegalStateException("No unique WebApplicationContext found: more than one " +
"DispatcherServlet registered with publishContext=true?");
}
wac = (WebApplicationContext) attrValue;
}
}
}
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
}
return wac;
| 521
| 275
| 796
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/util/SpringSecurityVersionUtils.java
|
SpringSecurityVersionUtils
|
getClass
|
class SpringSecurityVersionUtils {
private static final int SPRING_SECURITY_VERSION_MAJOR;
private static final int SPRING_SECURITY_VERSION_MINOR;
static {
String springSecurityVersion = SpringSecurityCoreVersion.getVersion();
// We will first compute the package name root for the spring framework in order to improve resilience
// against dependency renaming operations.
final String securityCorePackageName = SpringSecurityCoreVersion.class.getPackage().getName();
final String springSecurityPackageName =
securityCorePackageName.substring(0, securityCorePackageName.length() - 5); // - ".core"
// There might be times when SpringVersion cannot determine the version due to CL restrictions (see doc)
if (springSecurityVersion != null) {
try {
String versionRemainder = springSecurityVersion;
int separatorIdx = versionRemainder.indexOf('.');
SPRING_SECURITY_VERSION_MAJOR = Integer.parseInt(versionRemainder.substring(0, separatorIdx));
int separator2Idx = versionRemainder.indexOf('.', separatorIdx + 1);
SPRING_SECURITY_VERSION_MINOR = Integer.parseInt(versionRemainder.substring(separatorIdx + 1, separator2Idx));
} catch (final Exception e) {
throw new ExceptionInInitializerError(
"Exception during initialization of Spring Security versioning utilities. Identified Spring Security " +
"version is '" + springSecurityVersion + "', which does not follow the {major}.{minor}.{...} scheme");
}
} else {
if (testClassExistence(springSecurityPackageName + ".web.server.context.SecurityContextServerWebExchange")) {
SPRING_SECURITY_VERSION_MAJOR = 5;
SPRING_SECURITY_VERSION_MINOR = 0;
} else if (testClassExistence(springSecurityPackageName + ".jackson2.SecurityJackson2Modules")) {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 2;
} else if (testClassExistence(springSecurityPackageName + ".core.annotation.AuthenticationPrincipal")) {
// There are no new classes at the core of Spring Security 4.1, so we will check for a new
// "expression()" attribute method in the AuthenticationPrincipal annotation, which was added in 4.0
final Class<?> authenticationPrincipalClass =
getClass(springSecurityPackageName + ".core.annotation.AuthenticationPrincipal");
final Method[] methods = authenticationPrincipalClass.getDeclaredMethods();
boolean hasExpressionAttribute = false;
for (int i = 0; i < methods.length; i++) {
if ("expression".equals(methods[i].getName())) {
hasExpressionAttribute = true;
}
}
if (hasExpressionAttribute) {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 1;
} else {
SPRING_SECURITY_VERSION_MAJOR = 4;
SPRING_SECURITY_VERSION_MINOR = 0;
}
} else if (testClassExistence(springSecurityPackageName + ".access.method.P")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 2;
} else if (testClassExistence(springSecurityPackageName + ".provisioning.MutableUserDetails")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 1;
} else if (testClassExistence(springSecurityPackageName + ".access.expression.method.AbstractExpressionBasedMethodConfigAttribute")) {
SPRING_SECURITY_VERSION_MAJOR = 3;
SPRING_SECURITY_VERSION_MINOR = 0;
} else {
// We will default to 2.0
SPRING_SECURITY_VERSION_MAJOR = 2;
SPRING_SECURITY_VERSION_MINOR = 0;
}
}
}
private static boolean testClassExistence(final String className) {
final ClassLoader classLoader = ClassLoaderUtils.getClassLoader(SpringSecurityVersionUtils.class);
try {
Class.forName(className, false, classLoader);
return true;
} catch (final Throwable t) {
return false;
}
}
private static Class<?> getClass(final String className) {<FILL_FUNCTION_BODY>}
public static int getSpringSecurityVersionMajor() {
return SPRING_SECURITY_VERSION_MAJOR;
}
public static int getSpringSecurityVersionMinor() {
return SPRING_SECURITY_VERSION_MINOR;
}
public static boolean isSpringSecurity30AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 3;
}
public static boolean isSpringSecurity31AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 3 || (SPRING_SECURITY_VERSION_MAJOR == 3 && SPRING_SECURITY_VERSION_MINOR >= 1);
}
public static boolean isSpringSecurity32AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 3 || (SPRING_SECURITY_VERSION_MAJOR == 3 && SPRING_SECURITY_VERSION_MINOR >= 2);
}
public static boolean isSpringSecurity40AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 4;
}
public static boolean isSpringSecurity41AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 4 || (SPRING_SECURITY_VERSION_MAJOR == 4 && SPRING_SECURITY_VERSION_MINOR >= 1);
}
public static boolean isSpringSecurity42AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR > 4 || (SPRING_SECURITY_VERSION_MAJOR == 4 && SPRING_SECURITY_VERSION_MINOR >= 2);
}
public static boolean isSpringSecurity50AtLeast() {
return SPRING_SECURITY_VERSION_MAJOR >= 5;
}
private SpringSecurityVersionUtils() {
super();
}
}
|
final ClassLoader classLoader = ClassLoaderUtils.getClassLoader(SpringSecurityVersionUtils.class);
try {
return Class.forName(className, false, classLoader);
} catch (final Throwable t) {
return null;
}
| 1,684
| 66
| 1,750
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-extras-springsecurity6/src/main/java/org/thymeleaf/extras/springsecurity6/util/SpringVersionSpecificUtils.java
|
SpringVersionSpecificUtils
|
wrapEvaluationContext
|
class SpringVersionSpecificUtils {
private static final Logger LOG = LoggerFactory.getLogger(SpringVersionSpecificUtils.class);
private static final String PACKAGE_NAME = SpringVersionSpecificUtils.class.getPackage().getName();
// Spring Security 6 requires at least Spring 6
private static final String SPRING6_DELEGATE_CLASS = PACKAGE_NAME + ".Spring6VersionSpecificUtility";
private static final ISpringVersionSpecificUtility spring6Delegate;
static {
if (SpringVersionUtils.isSpring60AtLeast()) {
LOG.trace("[THYMELEAF][TESTING] Spring 6.0+ found on classpath. Initializing version-specific utilities for Spring 6");
try {
final Class<?> implClass = ClassLoaderUtils.loadClass(SPRING6_DELEGATE_CLASS);
spring6Delegate = (ISpringVersionSpecificUtility) implClass.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
throw new ExceptionInInitializerError(
new ConfigurationException(
"Environment has been detected to be at least Spring 6, but thymeleaf could not initialize a " +
"delegate of class \"" + SPRING6_DELEGATE_CLASS + "\"", e));
}
} else {
throw new ExceptionInInitializerError(
new ConfigurationException(
"The Spring-version-specific infrastructure could not create utility for the specific " +
"version of Spring being used. Currently only Spring 6.x or newer is supported."));
}
}
public static EvaluationContext wrapEvaluationContext(
final EvaluationContext evaluationContext, final IExpressionObjects expresionObjects) {<FILL_FUNCTION_BODY>}
public static boolean isWebContext(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.isWebContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
public static boolean isWebMvcContext(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.isWebMvcContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
public static boolean isWebFluxContext(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.isWebFluxContext(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
public static HttpServletRequest getHttpServletRequest(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.getHttpServletRequest(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
public static HttpServletResponse getHttpServletResponse(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.getHttpServletResponse(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
public static ServerWebExchange getServerWebExchange(final IContext context) {
if (spring6Delegate != null) {
return spring6Delegate.getServerWebExchange(context);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
}
private SpringVersionSpecificUtils() {
super();
}
}
|
if (spring6Delegate != null) {
return spring6Delegate.wrapEvaluationContext(evaluationContext, expresionObjects);
}
throw new ConfigurationException(
"The authorization infrastructure could not create initializer for the specific version of Spring being" +
"used. Currently only Spring 6.x or newer is supported.");
| 1,092
| 87
| 1,179
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/context/SpringContextUtils.java
|
SpringContextUtils
|
getApplicationContext
|
class SpringContextUtils {
/**
* <p>
* This is the name of the model attribute that will hold the (asychronously resolved)
* {@code WebSession} object in order to be used whenever needed, avoiding the need to block
* for obtaining it from the {@code ServerWebExchange}.
* </p>
* <p>
* Note resolving the {@code WebSession} from the reactive {@code Mono<WebSession>} stream does
* mean the creation of a {@code WebSession} instance, but not the real creation of a persisted session
* sent to the browser.
* </p>
* <p>
* Value: {@code "thymeleafWebSession"}
* </p>
*
* @see org.springframework.web.server.WebSession
*/
public static final String WEB_SESSION_ATTRIBUTE_NAME = "thymeleafWebSession";
/**
* <p>
* This is the name of the model attribute that will hold the (asychronously resolved)
* {@code Principal} object in order to be used whenever needed, avoiding the need to block
* for obtaining it from the {@code ServerWebExchange}.
* </p>
* <p>
* Value: {@code "thymeleafWebExchangePrincipal"}
* </p>
*
* @see org.springframework.web.server.ServerWebExchange
* @see java.security.Principal
*
* @since 3.1.0
*/
public static final String WEB_EXCHANGE_PRINCIPAL_ATTRIBUTE_NAME = "thymeleafWebExchangePrincipal";
/**
* <p>
* Get the {@link ApplicationContext} from the Thymeleaf template context.
* </p>
* <p>
* Note that the application context might not be always accessible (and thus this method
* can return {@code null}). Application Context will be accessible when the template is being executed
* as a Spring View, or else when an object of class {@link ThymeleafEvaluationContext} has been
* explicitly set into the {@link ITemplateContext} {@code context} with variable name
* {@link ThymeleafEvaluationContext#THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME}.
* </p>
*
* @param context the template context.
* @return the application context, or {@code null} if it could not be accessed.
*/
public static ApplicationContext getApplicationContext(final ITemplateContext context) {<FILL_FUNCTION_BODY>}
/**
* <p>
* Get the {@link IThymeleafRequestContext} from the Thymeleaf context.
* </p>
* <p>
* The returned object is a wrapper on the Spring request context that hides the fact of this request
* context corresponding to a Spring WebMVC or Spring WebFlux application.
* </p>
* <p>
* This will be done by looking for a context variable called
* {@link SpringContextVariableNames#THYMELEAF_REQUEST_CONTEXT}.
* </p>
*
* @param context the context
* @return the thymeleaf request context
*/
public static IThymeleafRequestContext getRequestContext(final IExpressionContext context) {
if (context == null) {
return null;
}
return (IThymeleafRequestContext) context.getVariable(SpringContextVariableNames.THYMELEAF_REQUEST_CONTEXT);
}
private SpringContextUtils() {
super();
}
}
|
if (context == null) {
return null;
}
// The ThymeleafEvaluationContext is set into the model by ThymeleafView (or wrapped by the SPEL evaluator)
final IThymeleafEvaluationContext evaluationContext =
(IThymeleafEvaluationContext) context.getVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME);
if (evaluationContext == null || !(evaluationContext instanceof ThymeleafEvaluationContext)) {
return null;
}
// Only when the evaluation context is a ThymeleafEvaluationContext we can access the ApplicationContext.
// The reason is it could also be a wrapper on another EvaluationContext implementation, created at the
// SPELVariableExpressionEvaluator on-the-fly (where ApplicationContext is not available because there might
// even not exist one), instead of at ThymeleafView (where we are sure we are executing a Spring View and
// have an ApplicationContext available).
return ((ThymeleafEvaluationContext)evaluationContext).getApplicationContext();
| 947
| 277
| 1,224
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/context/webflux/ReactiveContextVariableUtils.java
|
ReactiveContextVariableUtils
|
computePublisherValue
|
class ReactiveContextVariableUtils {
/**
* <p>
* Lazily resolve the reactive asynchronous object into a {@link Publisher}.
* </p>
* <p>
* The main aim of this method is to mirror the mechanism used by Spring for resolving
* asynchronous variables at the model of views (see Spring's
* {@link org.springframework.web.reactive.result.view.ViewResolutionResultHandler}):
* </p>
* <ul>
* <li>{@code Flux<T>} or other <em>multi-valued</em> streams are resolved as
* {@code List<T>} so that they are <em>iterable</em>.</li>
* <li>{@code Mono<T>} or other <em>single-valued</em> streams are resolved as
* {@code T} so that they are directly referenceable just like any other object.</li>
* </ul>
*
* @param asyncObj the asynchronous object being wrapped by this lazy variable.
* @param reactiveAdapterRegistry the Spring {@link ReactiveAdapterRegistry}.
* @return the resolved {@link Publisher}.
*/
static Publisher<Object> computePublisherValue(
final Object asyncObj, final ReactiveAdapterRegistry reactiveAdapterRegistry) {<FILL_FUNCTION_BODY>}
private ReactiveContextVariableUtils() {
super();
}
}
|
if (asyncObj instanceof Flux<?> || asyncObj instanceof Mono<?>) {
// If the async object is a Flux or a Mono, we don't need the ReactiveAdapterRegistry (and we allow
// initialization to happen without the registry, which is not possible with other Publisher<?>
// implementations.
return (Publisher<Object>) asyncObj;
}
if (reactiveAdapterRegistry == null) {
throw new IllegalArgumentException(
"Could not initialize lazy reactive context variable (data driver or explicitly-set " +
"reactive wrapper): Value is of class " + asyncObj.getClass().getName() +", but no " +
"ReactiveAdapterRegistry has been set. This can happen if this context variable is used " +
"for rendering a template without going through a " +
ThymeleafReactiveView.class.getSimpleName() + " or if there is no " +
"ReactiveAdapterRegistry bean registered at the application context. In such cases, it is " +
"required that the wrapped lazy variable values are instances of either " +
Flux.class.getName() + " or " + Mono.class.getName() + ".");
}
final ReactiveAdapter adapter = reactiveAdapterRegistry.getAdapter(null, asyncObj);
if (adapter != null) {
final Publisher<Object> publisher = adapter.toPublisher(asyncObj);
if (adapter.isMultiValue()) {
return Flux.from(publisher);
} else {
return Mono.from(publisher);
}
}
throw new IllegalArgumentException(
"Reactive context variable (data driver or explicitly-set reactive wrapper) is of " +
"class " + asyncObj.getClass().getName() +", but the ReactiveAdapterRegistry " +
"does not contain a valid adapter able to convert it into a supported reactive data stream.");
| 375
| 467
| 842
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/context/webflux/SpringWebFluxThymeleafRequestDataValueProcessor.java
|
SpringWebFluxThymeleafRequestDataValueProcessor
|
getExtraHiddenFields
|
class SpringWebFluxThymeleafRequestDataValueProcessor implements IThymeleafRequestDataValueProcessor {
private final RequestDataValueProcessor requestDataValueProcessor;
private final ServerWebExchange exchange;
SpringWebFluxThymeleafRequestDataValueProcessor(
final RequestDataValueProcessor requestDataValueProcessor, final ServerWebExchange exchange) {
super();
this.requestDataValueProcessor = requestDataValueProcessor;
this.exchange = exchange;
}
@Override
public String processAction(final String action, final String httpMethod) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return action;
}
return this.requestDataValueProcessor.processAction(this.exchange, action, httpMethod);
}
@Override
public String processFormFieldValue(final String name, final String value, final String type) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return value;
}
return this.requestDataValueProcessor.processFormFieldValue(this.exchange, name, value, type);
}
@Override
public Map<String, String> getExtraHiddenFields() {<FILL_FUNCTION_BODY>}
@Override
public String processUrl(final String url) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return url;
}
return this.requestDataValueProcessor.processUrl(this.exchange, url);
}
}
|
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return null;
}
return this.requestDataValueProcessor.getExtraHiddenFields(this.exchange);
| 403
| 60
| 463
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/context/webmvc/SpringWebMvcThymeleafRequestDataValueProcessor.java
|
SpringWebMvcThymeleafRequestDataValueProcessor
|
processUrl
|
class SpringWebMvcThymeleafRequestDataValueProcessor implements IThymeleafRequestDataValueProcessor {
private final RequestDataValueProcessor requestDataValueProcessor;
private final HttpServletRequest httpServletRequest;
SpringWebMvcThymeleafRequestDataValueProcessor(
final RequestDataValueProcessor requestDataValueProcessor, final HttpServletRequest httpServletRequest) {
super();
this.requestDataValueProcessor = requestDataValueProcessor;
this.httpServletRequest = httpServletRequest;
}
@Override
public String processAction(final String action, final String httpMethod) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return action;
}
return this.requestDataValueProcessor.processAction(this.httpServletRequest, action, httpMethod);
}
@Override
public String processFormFieldValue(final String name, final String value, final String type) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return value;
}
return this.requestDataValueProcessor.processFormFieldValue(this.httpServletRequest, name, value, type);
}
@Override
public Map<String, String> getExtraHiddenFields() {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return null;
}
return this.requestDataValueProcessor.getExtraHiddenFields(this.httpServletRequest);
}
@Override
public String processUrl(final String url) {<FILL_FUNCTION_BODY>}
}
|
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return url;
}
return this.requestDataValueProcessor.processUrl(this.httpServletRequest, url);
| 414
| 60
| 474
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/Mvc.java
|
Spring41MethodArgumentBuilderWrapper
|
encode
|
class Spring41MethodArgumentBuilderWrapper implements MethodArgumentBuilderWrapper {
private final org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodArgumentBuilder builder;
private Spring41MethodArgumentBuilderWrapper(
final org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodArgumentBuilder builder) {
super();
this.builder = builder;
}
public MethodArgumentBuilderWrapper arg(final int index, final Object value) {
return new Spring41MethodArgumentBuilderWrapper(this.builder.arg(index, value));
}
public MethodArgumentBuilderWrapper encode() {<FILL_FUNCTION_BODY>}
public String build() {
return this.builder.build();
}
public String buildAndExpand(final Object... uriVariables) {
return this.builder.buildAndExpand(uriVariables);
}
}
|
if (!SpringVersionUtils.isSpringAtLeast(5,0,8)) {
throw new IllegalStateException(String.format(
"At least Spring version 5.0.8.RELEASE is needed for executing " +
"MvcUriComponentsBuilder#encode() but detected Spring version is %s.",
SpringVersionUtils.getSpringVersion()));
}
return new Spring41MethodArgumentBuilderWrapper(this.builder.encode());
| 236
| 112
| 348
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/SPELContextMapWrapper.java
|
SPELContextMapWrapper
|
containsKey
|
class SPELContextMapWrapper implements Map {
private static final String REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME = "param";
private final IContext context;
private final IThymeleafEvaluationContext evaluationContext;
SPELContextMapWrapper(final IContext context, final IThymeleafEvaluationContext evaluationContext) {
super();
this.context = context;
this.evaluationContext = evaluationContext;
}
public int size() {
throw new TemplateProcessingException(
"Cannot call #size() on an " + IContext.class.getSimpleName() + " implementation");
}
public boolean isEmpty() {
throw new TemplateProcessingException(
"Cannot call #isEmpty() on an " + IContext.class.getSimpleName() + " implementation");
}
public boolean containsKey(final Object key) {<FILL_FUNCTION_BODY>}
public boolean containsValue(final Object value) {
throw new TemplateProcessingException(
"Cannot call #containsValue(value) on an " + IContext.class.getSimpleName() + " implementation");
}
public Object get(final Object key) {
if (this.context == null) {
throw new TemplateProcessingException("Cannot read property on null target");
}
return this.context.getVariable(key == null? null : key.toString());
}
public Object put(final Object key, final Object value) {
throw new TemplateProcessingException(
"Cannot call #put(key,value) on an " + IContext.class.getSimpleName() + " implementation");
}
public Object remove(final Object key) {
throw new TemplateProcessingException(
"Cannot call #remove(key) on an " + IContext.class.getSimpleName() + " implementation");
}
public void putAll(final Map m) {
throw new TemplateProcessingException(
"Cannot call #putAll(m) on an " + IContext.class.getSimpleName() + " implementation");
}
public void clear() {
throw new TemplateProcessingException(
"Cannot call #clear() on an " + IContext.class.getSimpleName() + " implementation");
}
public Set keySet() {
throw new TemplateProcessingException(
"Cannot call #keySet() on an " + IContext.class.getSimpleName() + " implementation");
}
public Collection values() {
throw new TemplateProcessingException(
"Cannot call #values() on an " + IContext.class.getSimpleName() + " implementation");
}
public Set<Entry> entrySet() {
throw new TemplateProcessingException(
"Cannot call #entrySet() on an " + IContext.class.getSimpleName() + " implementation");
}
}
|
if (this.evaluationContext.isVariableAccessRestricted()) {
if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(key)) {
throw new TemplateProcessingException(
"Access to variable \"" + key + "\" is forbidden in this context. Note some restrictions apply to " +
"variable access. For example, direct access to request parameters is forbidden in preprocessing and " +
"unescaped expressions, in TEXT template mode, in fragment insertion specifications and " +
"in some specific attribute processors.");
}
}
// We will be NOT calling this.context.containsVariable(key) as it could be very inefficient in web
// environments (based on HttpServletRequest#getAttributeName()), so we will just consider that every possible
// element exists in an IContext, and simply return null for those not found
return this.context != null;
| 751
| 222
| 973
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/SPELContextPropertyAccessor.java
|
SPELContextPropertyAccessor
|
read
|
class SPELContextPropertyAccessor implements PropertyAccessor {
private static final Logger LOGGER = LoggerFactory.getLogger(SPELContextPropertyAccessor.class);
static final SPELContextPropertyAccessor INSTANCE = new SPELContextPropertyAccessor();
private static final String REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME = "param";
private static final Class<?>[] TARGET_CLASSES = new Class<?>[] { IContext.class };
SPELContextPropertyAccessor() {
super();
}
public Class<?>[] getSpecificTargetClasses() {
return TARGET_CLASSES;
}
public boolean canRead(final EvaluationContext context, final Object target, final String name)
throws AccessException {
if (context instanceof IThymeleafEvaluationContext) {
if (((IThymeleafEvaluationContext) context).isVariableAccessRestricted()) {
if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(name)) {
throw new AccessException(
"Access to variable \"" + name + "\" is forbidden in this context. Note some restrictions apply to " +
"variable access. For example, direct access to request parameters is forbidden in preprocessing and " +
"unescaped expressions, in TEXT template mode, in fragment insertion specifications and " +
"in some specific attribute processors.");
}
}
}
return target != null;
}
public TypedValue read(final EvaluationContext evaluationContext, final Object target, final String name)
throws AccessException {<FILL_FUNCTION_BODY>}
public boolean canWrite(
final EvaluationContext context, final Object target, final String name)
throws AccessException {
// There should never be a need to write on an IContext during a template execution
return false;
}
public void write(
final EvaluationContext context, final Object target, final String name, final Object newValue)
throws AccessException {
// There should never be a need to write on an IContext during a template execution
throw new AccessException("Cannot write to " + IContext.class.getName());
}
}
|
if (target == null) {
throw new AccessException("Cannot read property of null target");
}
try {
final IContext context = (IContext) target;
return new TypedValue(context.getVariable(name));
} catch (final ClassCastException e) {
// This can happen simply because we're applying the same
// AST tree on a different class (Spring internally caches property accessors).
// So this exception might be considered "normal" by Spring AST evaluator and
// just use it to refresh the property accessor cache.
throw new AccessException("Cannot read target of class " + target.getClass().getName());
}
| 572
| 170
| 742
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/SpringStandardConversionService.java
|
SpringStandardConversionService
|
convertToString
|
class SpringStandardConversionService extends AbstractStandardConversionService {
private static final TypeDescriptor TYPE_STRING = TypeDescriptor.valueOf(String.class);
public SpringStandardConversionService() {
// Should only be instanced from SpringStandardDialect
super();
}
@Override
protected String convertToString(
final IExpressionContext context,
final Object object) {<FILL_FUNCTION_BODY>}
@Override
protected <T> T convertOther(
final IExpressionContext context,
final Object object, final Class<T> targetClass) {
if (object == null) {
return null;
}
final TypeDescriptor objectTypeDescriptor = TypeDescriptor.forObject(object);
final TypeDescriptor targetTypeDescriptor = TypeDescriptor.valueOf(targetClass);
final TypeConverter typeConverter = getSpringConversionService(context);
if (typeConverter == null || !typeConverter.canConvert(objectTypeDescriptor, targetTypeDescriptor)) {
return super.convertOther(context, object, targetClass);
}
return (T) typeConverter.convertValue(object, objectTypeDescriptor, targetTypeDescriptor);
}
private static TypeConverter getSpringConversionService(final IExpressionContext context) {
final EvaluationContext evaluationContext =
(EvaluationContext) context.getVariable(
ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME);
if (evaluationContext != null) {
return evaluationContext.getTypeConverter();
}
return null;
}
}
|
if (object == null) {
return null;
}
final TypeDescriptor objectTypeDescriptor = TypeDescriptor.forObject(object);
final TypeConverter typeConverter = getSpringConversionService(context);
if (typeConverter == null || !typeConverter.canConvert(objectTypeDescriptor, TYPE_STRING)) {
return super.convertToString(context, object);
}
return (String) typeConverter.convertValue(object, objectTypeDescriptor, TYPE_STRING);
| 413
| 118
| 531
|
<methods>public final T convert(org.thymeleaf.context.IExpressionContext, java.lang.Object, Class<T>) <variables>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/SpringStandardExpressionObjectFactory.java
|
SpringStandardExpressionObjectFactory
|
buildObject
|
class SpringStandardExpressionObjectFactory extends StandardExpressionObjectFactory {
/*
* Any new objects added here should also be added to the "ALL_EXPRESSION_OBJECT_NAMES" See below.
*/
public static final String FIELDS_EXPRESSION_OBJECT_NAME = "fields";
public static final String THEMES_EXPRESSION_OBJECT_NAME = "themes";
public static final String MVC_EXPRESSION_OBJECT_NAME = "mvc";
public static final String REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME = "requestdatavalues";
public static final Set<String> ALL_EXPRESSION_OBJECT_NAMES;
private static final Mvc MVC_EXPRESSION_OBJECT = new Mvc();
static {
final Set<String> allExpressionObjectNames = new LinkedHashSet<String>();
allExpressionObjectNames.addAll(StandardExpressionObjectFactory.ALL_EXPRESSION_OBJECT_NAMES);
allExpressionObjectNames.add(FIELDS_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(THEMES_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(MVC_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME);
ALL_EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(allExpressionObjectNames);
}
public SpringStandardExpressionObjectFactory() {
super();
}
public Set<String> getAllExpressionObjectNames() {
return ALL_EXPRESSION_OBJECT_NAMES;
}
public Object buildObject(final IExpressionContext context, final String expressionObjectName) {<FILL_FUNCTION_BODY>}
}
|
if (MVC_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
return MVC_EXPRESSION_OBJECT;
}
if (THEMES_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
return new Themes(context);
}
if (FIELDS_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
return new Fields(context);
}
if (REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (context instanceof ITemplateContext) {
return new RequestDataValues((ITemplateContext)context);
}
return null;
}
return super.buildObject(context, expressionObjectName);
| 466
| 195
| 661
|
<methods>public void <init>() ,public java.lang.Object buildObject(org.thymeleaf.context.IExpressionContext, java.lang.String) ,public Set<java.lang.String> getAllExpressionObjectNames() ,public boolean isCacheable(java.lang.String) <variables>private static final org.thymeleaf.expression.Aggregates AGGREGATES_EXPRESSION_OBJECT,public static final java.lang.String AGGREGATES_EXPRESSION_OBJECT_NAME,protected static final Set<java.lang.String> ALL_EXPRESSION_OBJECT_NAMES,private static final org.thymeleaf.expression.Arrays ARRAYS_EXPRESSION_OBJECT,public static final java.lang.String ARRAYS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Bools BOOLS_EXPRESSION_OBJECT,public static final java.lang.String BOOLS_EXPRESSION_OBJECT_NAME,public static final java.lang.String CALENDARS_EXPRESSION_OBJECT_NAME,public static final java.lang.String CONTEXT_EXPRESSION_OBJECT_NAME,public static final java.lang.String CONVERSIONS_EXPRESSION_OBJECT_NAME,public static final java.lang.String DATES_EXPRESSION_OBJECT_NAME,public static final java.lang.String EXECUTION_INFO_OBJECT_NAME,public static final java.lang.String IDS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Lists LISTS_EXPRESSION_OBJECT,public static final java.lang.String LISTS_EXPRESSION_OBJECT_NAME,public static final java.lang.String LOCALE_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Maps MAPS_EXPRESSION_OBJECT,public static final java.lang.String MAPS_EXPRESSION_OBJECT_NAME,public static final java.lang.String MESSAGES_EXPRESSION_OBJECT_NAME,public static final java.lang.String NUMBERS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Objects OBJECTS_EXPRESSION_OBJECT,public static final java.lang.String OBJECTS_EXPRESSION_OBJECT_NAME,public static final java.lang.String REQUEST_EXPRESSION_OBJECT_NAME,public static final java.lang.String RESPONSE_EXPRESSION_OBJECT_NAME,public static final java.lang.String ROOT_EXPRESSION_OBJECT_NAME,public static final java.lang.String SELECTION_TARGET_EXPRESSION_OBJECT_NAME,public static final java.lang.String SERVLET_CONTEXT_EXPRESSION_OBJECT_NAME,public static final java.lang.String SESSION_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Sets SETS_EXPRESSION_OBJECT,public static final java.lang.String SETS_EXPRESSION_OBJECT_NAME,public static final java.lang.String STRINGS_EXPRESSION_OBJECT_NAME,public static final java.lang.String TEMPORALS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Uris URIS_EXPRESSION_OBJECT,public static final java.lang.String URIS_EXPRESSION_OBJECT_NAME,public static final java.lang.String VARIABLES_EXPRESSION_OBJECT_NAME
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/SpringStandardExpressions.java
|
SpringStandardExpressions
|
isSpringELCompilerEnabled
|
class SpringStandardExpressions {
/**
* Name used for registering whether <i>Spring EL compilation</i> should be enabled if available or not.
*/
public static final String ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME = "EnableSpringELCompiler";
private SpringStandardExpressions() {
super();
}
/**
* <p>
* Check whether compilation of Spring EL expressions should be enabled or not.
* </p>
* <p>
* This is done through configuration methods at the {@link SpringStandardDialect}
* instance being used, and its value is offered to the engine as an <em>execution attribute</em>.
* </p>
*
* @param configuration the configuration object for the current template execution environment.
* @return {@code true} if the SpEL compiler should be enabled if available, {@code false} if not.
*/
public static boolean isSpringELCompilerEnabled(final IEngineConfiguration configuration) {<FILL_FUNCTION_BODY>}
}
|
final Object enableSpringELCompiler =
configuration.getExecutionAttributes().get(ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME);
if (enableSpringELCompiler == null) {
return false;
}
if (!(enableSpringELCompiler instanceof Boolean)) {
throw new TemplateProcessingException(
"A value for the \"" + ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME + "\" execution attribute " +
"has been specified, but it is not of the required type Boolean. " +
"(" + enableSpringELCompiler.getClass().getName() + ")");
}
return ((Boolean) enableSpringELCompiler).booleanValue();
| 280
| 178
| 458
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/Themes.java
|
Themes
|
code
|
class Themes {
private final Theme theme;
private final Locale locale;
/**
* Constructor, obtains the current theme and locale from the processing
* context for code lookups later.
*
* @param context the processing context being used
*/
public Themes(final IExpressionContext context) {
super();
this.locale = context.getLocale();
final IThymeleafRequestContext requestContext = SpringContextUtils.getRequestContext(context);
this.theme = requestContext != null ? requestContext.getTheme() : null;
}
/**
* Looks up and returns the value of the given key in the properties file of
* the currently-selected theme.
*
* @param code Key to look up in the theme properties file.
* @return The value of the code in the current theme properties file, or an
* empty string if the code could not be resolved.
*/
public String code(final String code) {<FILL_FUNCTION_BODY>}
}
|
if (this.theme == null) {
throw new TemplateProcessingException("Theme cannot be resolved because RequestContext was not found. "
+ "Are you using a Context object without a RequestContext variable?");
}
return this.theme.getMessageSource().getMessage(code, null, "", this.locale);
| 264
| 76
| 340
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/ThymeleafEvaluationContext.java
|
ThymeleafEvaluationContextACLPropertyAccessor
|
canRead
|
class ThymeleafEvaluationContextACLPropertyAccessor extends ReflectivePropertyAccessor {
private final ReflectivePropertyAccessor propertyAccessor;
ThymeleafEvaluationContextACLPropertyAccessor() {
this(null);
}
ThymeleafEvaluationContextACLPropertyAccessor(final ReflectivePropertyAccessor propertyAccessor) {
super(false); // allowWrite = false
// propertyAccessor CAN be null
this.propertyAccessor = propertyAccessor;
}
@Override
public boolean canRead(final EvaluationContext context, final Object targetObject, final String name) throws AccessException {<FILL_FUNCTION_BODY>}
}
|
final boolean canRead;
if (this.propertyAccessor != null) {
canRead = this.propertyAccessor.canRead(context, targetObject, name);
} else {
canRead = super.canRead(context, targetObject, name);
}
if (canRead) {
// We need to perform the check on the getter equivalent to the member being called
final String methodEquiv =
("empty".equals(name) || "blank".equals(name)) ?
"is" + Character.toUpperCase(name.charAt(0)) + name.substring(1) :
"get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
if (!ExpressionUtils.isMemberAllowed(targetObject, methodEquiv)) {
throw new EvaluationException(
String.format(
"Accessing member '%s' is forbidden for type '%s' in this expression context.",
name, targetObject.getClass()));
}
}
return canRead;
| 174
| 263
| 437
|
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public void addConstructorResolver(org.springframework.expression.ConstructorResolver) ,public void addMethodResolver(org.springframework.expression.MethodResolver) ,public void addPropertyAccessor(org.springframework.expression.PropertyAccessor) ,public org.springframework.expression.BeanResolver getBeanResolver() ,public List<org.springframework.expression.ConstructorResolver> getConstructorResolvers() ,public List<org.springframework.expression.MethodResolver> getMethodResolvers() ,public org.springframework.expression.OperatorOverloader getOperatorOverloader() ,public List<org.springframework.expression.PropertyAccessor> getPropertyAccessors() ,public org.springframework.expression.TypedValue getRootObject() ,public org.springframework.expression.TypeComparator getTypeComparator() ,public org.springframework.expression.TypeConverter getTypeConverter() ,public org.springframework.expression.TypeLocator getTypeLocator() ,public java.lang.Object lookupVariable(java.lang.String) ,public void registerFunction(java.lang.String, java.lang.reflect.Method) ,public void registerMethodFilter(Class<?>, org.springframework.expression.MethodFilter) throws java.lang.IllegalStateException,public boolean removeConstructorResolver(org.springframework.expression.ConstructorResolver) ,public boolean removeMethodResolver(org.springframework.expression.MethodResolver) ,public boolean removePropertyAccessor(org.springframework.expression.PropertyAccessor) ,public void setBeanResolver(org.springframework.expression.BeanResolver) ,public void setConstructorResolvers(List<org.springframework.expression.ConstructorResolver>) ,public void setMethodResolvers(List<org.springframework.expression.MethodResolver>) ,public void setOperatorOverloader(org.springframework.expression.OperatorOverloader) ,public void setPropertyAccessors(List<org.springframework.expression.PropertyAccessor>) ,public void setRootObject(java.lang.Object) ,public void setRootObject(java.lang.Object, org.springframework.core.convert.TypeDescriptor) ,public void setTypeComparator(org.springframework.expression.TypeComparator) ,public void setTypeConverter(org.springframework.expression.TypeConverter) ,public void setTypeLocator(org.springframework.expression.TypeLocator) ,public void setVariable(java.lang.String, java.lang.Object) ,public void setVariables(Map<java.lang.String,java.lang.Object>) <variables>private org.springframework.expression.BeanResolver beanResolver,private volatile List<org.springframework.expression.ConstructorResolver> constructorResolvers,private volatile List<org.springframework.expression.MethodResolver> methodResolvers,private org.springframework.expression.OperatorOverloader operatorOverloader,private volatile List<org.springframework.expression.PropertyAccessor> propertyAccessors,private volatile org.springframework.expression.spel.support.ReflectiveMethodResolver reflectiveMethodResolver,private org.springframework.expression.TypedValue rootObject,private org.springframework.expression.TypeComparator typeComparator,private org.springframework.expression.TypeConverter typeConverter,private org.springframework.expression.TypeLocator typeLocator,private final Map<java.lang.String,java.lang.Object> variables
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/expression/ThymeleafEvaluationContextWrapper.java
|
ThymeleafEvaluationContextWrapper
|
lookupVariable
|
class ThymeleafEvaluationContextWrapper implements IThymeleafEvaluationContext {
private static final MapAccessor MAP_ACCESSOR_INSTANCE = new MapAccessor();
private final EvaluationContext delegate;
private final List<PropertyAccessor> propertyAccessors; // can be initialized to null if we can delegate
private final TypeLocator typeLocator; // can be initialized to null if we can delegate
private final List<MethodResolver> methodResolvers; // can be initialized to null if we can delegate
private IExpressionObjects expressionObjects = null;
private boolean requestParametersRestricted = false;
private Map<String,Object> additionalVariables = null;
public ThymeleafEvaluationContextWrapper(final EvaluationContext delegate) {
super();
Validate.notNull(delegate, "Evaluation context delegate cannot be null");
this.delegate = delegate;
if (this.delegate instanceof ThymeleafEvaluationContext) {
this.propertyAccessors = null; // No need to initialize our own property accessors
this.typeLocator = null; // No need to initialize our own type locator
this.methodResolvers = null; // No need to initialize our own method resolvers
} else {
// We need to wrap any reflective method resolvers in order to forbid calling methods on any of the blocked classes
this.propertyAccessors =
Stream.concat(
Stream.of(SPELContextPropertyAccessor.INSTANCE, MAP_ACCESSOR_INSTANCE),
this.delegate.getPropertyAccessors().stream()
.map(pa -> (pa instanceof ReflectivePropertyAccessor) ?
new ThymeleafEvaluationContextACLPropertyAccessor((ReflectivePropertyAccessor) pa) : pa))
.collect(Collectors.toList());
// We need to establish a custom type locator in order to forbid access to certain dangerous classes in expressions
this.typeLocator =
new ThymeleafEvaluationContextACLTypeLocator(this.delegate.getTypeLocator());
// We need to wrap any reflective method resolvers in order to forbid calling methods on any of the blocked classes
this.methodResolvers =
this.delegate.getMethodResolvers().stream()
.map(mr -> (mr instanceof ReflectiveMethodResolver) ?
new ThymeleafEvaluationContextACLMethodResolver((ReflectiveMethodResolver) mr) : mr)
.collect(Collectors.toList());
}
}
public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
public List<MethodResolver> getMethodResolvers() {
return this.methodResolvers == null ? this.delegate.getMethodResolvers() : this.methodResolvers;
}
public List<PropertyAccessor> getPropertyAccessors() {
return this.propertyAccessors == null ? this.delegate.getPropertyAccessors() : this.propertyAccessors;
}
public TypeLocator getTypeLocator() {
return this.typeLocator == null ? this.delegate.getTypeLocator() : this.typeLocator;
}
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
public BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
public void setVariable(final String name, final Object value) {
if (this.additionalVariables == null) {
this.additionalVariables = new HashMap<String, Object>(5, 1.0f);
}
this.additionalVariables.put(name, value);
}
public Object lookupVariable(final String name) {<FILL_FUNCTION_BODY>}
public boolean isVariableAccessRestricted() {
return this.requestParametersRestricted;
}
public void setVariableAccessRestricted(final boolean restricted) {
this.requestParametersRestricted = restricted;
}
public IExpressionObjects getExpressionObjects() {
return this.expressionObjects;
}
public void setExpressionObjects(final IExpressionObjects expressionObjects) {
this.expressionObjects = expressionObjects;
}
}
|
if (this.expressionObjects != null && this.expressionObjects.containsObject(name)) {
final Object result = this.expressionObjects.getObject(name);
if (result != null) {
return result;
}
}
if (this.additionalVariables != null && this.additionalVariables.containsKey(name)) {
final Object result = this.additionalVariables.get(name);
if (result != null) {
return result;
}
}
// fall back to delegate
return this.delegate.lookupVariable(name);
| 1,173
| 154
| 1,327
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/messageresolver/SpringMessageResolver.java
|
SpringMessageResolver
|
resolveMessage
|
class SpringMessageResolver
extends AbstractMessageResolver
implements MessageSourceAware {
private static final Logger logger = LoggerFactory.getLogger(SpringMessageResolver.class);
private final StandardMessageResolver standardMessageResolver;
private MessageSource messageSource;
public SpringMessageResolver() {
super();
this.standardMessageResolver = new StandardMessageResolver();
}
/*
* Check the message source has been set.
*/
private void checkMessageSourceInitialized() {
if (this.messageSource == null) {
throw new ConfigurationException(
"Cannot initialize " + SpringMessageResolver.class.getSimpleName() +
": MessageSource has not been set. Either define this object as " +
"a Spring bean (which will automatically set the MessageSource) or, " +
"if you instance it directly, set the MessageSource manually using its "+
"corresponding setter method.");
}
}
/**
* <p>
* Returns the message source ({@link MessageSource}) to be
* used for message resolution.
* </p>
*
* @return the message source
*/
public final MessageSource getMessageSource() {
return this.messageSource;
}
/**
* <p>
* Sets the message source to be used for message resolution
* </p>
*
* @param messageSource the message source
*/
public final void setMessageSource(final MessageSource messageSource) {
this.messageSource = messageSource;
}
public final String resolveMessage(
final ITemplateContext context, final Class<?> origin, final String key, final Object[] messageParameters) {<FILL_FUNCTION_BODY>}
public String createAbsentMessageRepresentation(
final ITemplateContext context, final Class<?> origin, final String key, final Object[] messageParameters) {
return this.standardMessageResolver.createAbsentMessageRepresentation(context, origin, key, messageParameters);
}
}
|
Validate.notNull(context.getLocale(), "Locale in context cannot be null");
Validate.notNull(key, "Message key cannot be null");
/*
* FIRST STEP: Look for the message using template-based resolution
*/
if (context != null) {
checkMessageSourceInitialized();
if (logger.isTraceEnabled()) {
logger.trace(
"[THYMELEAF][{}] Resolving message with key \"{}\" for template \"{}\" and locale \"{}\". " +
"Messages will be retrieved from Spring's MessageSource infrastructure.",
new Object[]{TemplateEngine.threadIndex(), key, context.getTemplateData().getTemplate(), context.getLocale()});
}
try {
return this.messageSource.getMessage(key, messageParameters, context.getLocale());
} catch (NoSuchMessageException e) {
// Try other methods
}
}
/*
* SECOND STEP: Look for the message using origin-based resolution, delegated to the StandardMessageResolver
*/
if (origin != null) {
// We will be disabling template-based resolution when delegating in order to use only origin-based
final String message =
this.standardMessageResolver.resolveMessage(context, origin, key, messageParameters, false, true, true);
if (message != null) {
return message;
}
}
/*
* NOT FOUND, return null
*/
return null;
| 521
| 382
| 903
|
<methods>public final java.lang.String getName() ,public final java.lang.Integer getOrder() ,public void setName(java.lang.String) ,public void setOrder(java.lang.Integer) <variables>private static final org.slf4j.Logger logger,private java.lang.String name,private java.lang.Integer order
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/AbstractSpringFieldTagProcessor.java
|
AbstractSpringFieldTagProcessor
|
matchesDiscriminator
|
class AbstractSpringFieldTagProcessor
extends AbstractAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "field";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
protected static final String INPUT_TAG_NAME = "input";
protected static final String SELECT_TAG_NAME = "select";
protected static final String OPTION_TAG_NAME = "option";
protected static final String TEXTAREA_TAG_NAME = "textarea";
protected static final String ID_ATTR_NAME = "id";
protected static final String TYPE_ATTR_NAME = "type";
protected static final String NAME_ATTR_NAME = "name";
protected static final String VALUE_ATTR_NAME = "value";
protected static final String CHECKED_ATTR_NAME = "checked";
protected static final String SELECTED_ATTR_NAME = "selected";
protected static final String DISABLED_ATTR_NAME = "disabled";
protected static final String MULTIPLE_ATTR_NAME = "multiple";
private AttributeDefinition discriminatorAttributeDefinition;
protected AttributeDefinition idAttributeDefinition;
protected AttributeDefinition typeAttributeDefinition;
protected AttributeDefinition nameAttributeDefinition;
protected AttributeDefinition valueAttributeDefinition;
protected AttributeDefinition checkedAttributeDefinition;
protected AttributeDefinition selectedAttributeDefinition;
protected AttributeDefinition disabledAttributeDefinition;
protected AttributeDefinition multipleAttributeDefinition;
private final String discriminatorAttrName;
private final String[] discriminatorAttrValues;
private final boolean removeAttribute;
public AbstractSpringFieldTagProcessor(
final String dialectPrefix, final String elementName,
final String discriminatorAttrName, final String[] discriminatorAttrValues,
final boolean removeAttribute) {
super(TEMPLATE_MODE, dialectPrefix, elementName, false, ATTR_NAME, true, ATTR_PRECEDENCE, false);
this.discriminatorAttrName = discriminatorAttrName;
this.discriminatorAttrValues = discriminatorAttrValues;
this.removeAttribute = removeAttribute;
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions in order to being able to use much
// faster methods for setting/replacing attributes on the ElementAttributes implementation
this.discriminatorAttributeDefinition =
(this.discriminatorAttrName != null? attributeDefinitions.forName(TEMPLATE_MODE, this.discriminatorAttrName) : null);
this.idAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, ID_ATTR_NAME);
this.typeAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TYPE_ATTR_NAME);
this.nameAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, NAME_ATTR_NAME);
this.valueAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, VALUE_ATTR_NAME);
this.checkedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, CHECKED_ATTR_NAME);
this.selectedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, SELECTED_ATTR_NAME);
this.disabledAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, DISABLED_ATTR_NAME);
this.multipleAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, MULTIPLE_ATTR_NAME);
}
private boolean matchesDiscriminator(final IProcessableElementTag tag) {<FILL_FUNCTION_BODY>}
@Override
protected void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IElementTagStructureHandler structureHandler) {
/*
* First thing to check is whether this processor really matches, because so far we have asked the engine only
* to match per attribute (th:field) and host tag (input, select, option...) but we still don't know if the
* match is complete because we might still need to assess for example that the 'type' attribute has the
* correct value. For example, the same processor will not be executing on <input type="text" th:field="*{a}"/>
* and on <input type="checkbox" th:field="*{a}"/>
*/
if (!matchesDiscriminator(tag)) {
// Note in this case we do not have to remove the th:field attribute because the correct processor is still
// to be executed!
return;
}
if (this.removeAttribute) {
structureHandler.removeAttribute(attributeName);
}
final IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus == null) {
throw new TemplateProcessingException(
"Cannot process attribute '" + attributeName + "': no associated BindStatus could be found for " +
"the intended form binding operations. This can be due to the lack of a proper management of the " +
"Spring RequestContext, which is usually done through the ThymeleafView or ThymeleafReactiveView");
}
// We set the BindStatus into a local variable just in case we have more BindStatus-related processors to
// be applied for the same tag, like for example a th:errorclass
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
doProcess(context, tag, attributeName, attributeValue, bindStatus, structureHandler);
}
protected abstract void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName,
final String attributeValue,
final IThymeleafBindStatus bindStatus,
final IElementTagStructureHandler structureHandler);
// This method is designed to be called from the diverse subclasses
protected final String computeId(
final ITemplateContext context,
final IProcessableElementTag tag,
final String name, final boolean sequence) {
String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());
if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {
return (StringUtils.hasText(id) ? id : null);
}
id = FieldUtils.idFromName(name);
if (sequence) {
final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);
return id + count.toString();
}
return id;
}
}
|
if (this.discriminatorAttrName == null) {
return true;
}
final boolean hasDiscriminatorAttr = tag.hasAttribute(this.discriminatorAttributeDefinition.getAttributeName());
if (this.discriminatorAttrValues == null || this.discriminatorAttrValues.length == 0) {
return hasDiscriminatorAttr;
}
final String discriminatorTagValue =
(hasDiscriminatorAttr? tag.getAttributeValue(this.discriminatorAttributeDefinition.getAttributeName()) : null);
for (int i = 0; i < this.discriminatorAttrValues.length; i++) {
final String discriminatorAttrValue = this.discriminatorAttrValues[i];
if (discriminatorAttrValue == null) {
if (!hasDiscriminatorAttr || discriminatorTagValue == null) {
return true;
}
} else if (discriminatorAttrValue.equals(discriminatorTagValue)) {
return true;
}
}
return false;
| 1,731
| 270
| 2,001
|
<methods><variables>private final non-sealed boolean removeAttribute
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.