diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 8e6f28e3a8..426d65c32b 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -11,11 +11,15 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 + + 2.2.6.RELEASE + + org.springframework.boot diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java deleted file mode 100644 index 25cbb9bc9b..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.cassecuredapp; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; -import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; -import org.jasig.cas.client.validation.TicketValidator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.EventListener; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; - -import javax.servlet.http.HttpSessionEvent; - -@SpringBootApplication -public class CasSecuredAppApplication { - - public static void main(String[] args) { - SpringApplication.run(CasSecuredAppApplication.class, args); - } - - @Bean - public ServiceProperties serviceProperties() { - ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setService("http://localhost:9000/login/cas"); - serviceProperties.setSendRenew(false); - return serviceProperties; - } - - @Bean - @Primary - public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { - CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:6443/cas/login"); - entryPoint.setServiceProperties(sP); - return entryPoint; - } - - @Bean - public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); - } - - @Bean - public CasAuthenticationProvider casAuthenticationProvider() { - CasAuthenticationProvider provider = new CasAuthenticationProvider(); - provider.setServiceProperties(serviceProperties()); - provider.setTicketValidator(ticketValidator()); - provider.setUserDetailsService((s) -> new User("test@test.com", "smatt", - true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); - provider.setKey("CAS_PROVIDER_LOCALHOST_9000"); - return provider; - } - - - @Bean - public SecurityContextLogoutHandler securityContextLogoutHandler() { - return new SecurityContextLogoutHandler(); - } - - @Bean - public LogoutFilter logoutFilter() { - LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:6443/cas/logout", securityContextLogoutHandler()); - logoutFilter.setFilterProcessesUrl("/logout/cas"); - return logoutFilter; - } - - @Bean - public SingleSignOutFilter singleSignOutFilter() { - SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); - singleSignOutFilter.setIgnoreInitConfiguration(true); - return singleSignOutFilter; - } - - @EventListener - public SingleSignOutHttpSessionListener singleSignOutHttpSessionListener(HttpSessionEvent event) { - return new SingleSignOutHttpSessionListener(); - } -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java new file mode 100644 index 0000000000..4a2c609758 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -0,0 +1,97 @@ +package com.baeldung.cassecuredapp; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; + +import javax.servlet.http.HttpSessionEvent; + +@SpringBootApplication +public class CasSecuredApplication { + + private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class); + + public static void main(String... args) { + SpringApplication.run(CasSecuredApplication.class, args); + } + + @Bean + public CasAuthenticationFilter casAuthenticationFilter( + AuthenticationManager authenticationManager, + ServiceProperties serviceProperties) throws Exception { + CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setAuthenticationManager(authenticationManager); + filter.setServiceProperties(serviceProperties); + return filter; + } + + @Bean + public ServiceProperties serviceProperties() { + logger.info("service properties"); + ServiceProperties serviceProperties = new ServiceProperties(); + serviceProperties.setService("http://cas-client:8900/login/cas"); + serviceProperties.setSendRenew(false); + return serviceProperties; + } + + @Bean + public TicketValidator ticketValidator() { + return new Cas30ServiceTicketValidator("https://localhost:8443"); + } + + @Bean + public CasAuthenticationProvider casAuthenticationProvider( + TicketValidator ticketValidator, + ServiceProperties serviceProperties) { + CasAuthenticationProvider provider = new CasAuthenticationProvider(); + provider.setServiceProperties(serviceProperties); + provider.setTicketValidator(ticketValidator); + provider.setUserDetailsService( + s -> new User("test@test.com", "Mellon", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); + return provider; + } + + + @Bean + public SecurityContextLogoutHandler securityContextLogoutHandler() { + return new SecurityContextLogoutHandler(); + } + + @Bean + public LogoutFilter logoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/logout", securityContextLogoutHandler()); + logoutFilter.setFilterProcessesUrl("/logout/cas"); + return logoutFilter; + } + + @Bean + public SingleSignOutFilter singleSignOutFilter() { + SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443"); + singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); + singleSignOutFilter.setIgnoreInitConfiguration(true); + return singleSignOutFilter; + } + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java deleted file mode 100644 index 2eabed49e1..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.cassecuredapp.config; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.ProviderManager; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationFilter; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; - -import java.util.Arrays; - -@EnableWebSecurity -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private AuthenticationProvider authenticationProvider; - private AuthenticationEntryPoint authenticationEntryPoint; - private SingleSignOutFilter singleSignOutFilter; - private LogoutFilter logoutFilter; - - @Autowired - public SecurityConfig(CasAuthenticationProvider casAuthenticationProvider, AuthenticationEntryPoint eP, - LogoutFilter lF - , SingleSignOutFilter ssF - ) { - this.authenticationProvider = casAuthenticationProvider; - this.authenticationEntryPoint = eP; - - this.logoutFilter = lF; - this.singleSignOutFilter = ssF; - - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .regexMatchers("/secured.*", "/login") - .authenticated() - .and() - .authorizeRequests() - .regexMatchers("/") - .permitAll() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint) - .and() - .logout().logoutSuccessUrl("/logout") - .and() - .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) - .addFilterBefore(logoutFilter, LogoutFilter.class); - - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider); - } - - @Override - protected AuthenticationManager authenticationManager() throws Exception { - return new ProviderManager(Arrays.asList(authenticationProvider)); - } - - @Bean - public CasAuthenticationFilter casAuthenticationFilter(ServiceProperties sP) throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setServiceProperties(sP); - filter.setAuthenticationManager(authenticationManager()); - return filter; - } - -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java new file mode 100644 index 0000000000..b0c3c68387 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java @@ -0,0 +1,79 @@ +package com.baeldung.cassecuredapp.config; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.logout.LogoutFilter; + +import java.util.Collections; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class); + private SingleSignOutFilter singleSignOutFilter; + private LogoutFilter logoutFilter; + private CasAuthenticationProvider casAuthenticationProvider; + private ServiceProperties serviceProperties; + + @Autowired + public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter, + CasAuthenticationProvider casAuthenticationProvider, + ServiceProperties serviceProperties) { + this.logoutFilter = logoutFilter; + this.singleSignOutFilter = singleSignOutFilter; + this.serviceProperties = serviceProperties; + this.casAuthenticationProvider = casAuthenticationProvider; + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) + .and() + .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) + .addFilterBefore(logoutFilter, LogoutFilter.class) + .csrf().ignoringAntMatchers("/exit/cas"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(casAuthenticationProvider); + } + + @Bean + @Override + protected AuthenticationManager authenticationManager() throws Exception { + return new ProviderManager(Collections.singletonList(casAuthenticationProvider)); + } + + public AuthenticationEntryPoint authenticationEntryPoint() { + CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); + entryPoint.setLoginUrl("https://localhost:8443/login"); + entryPoint.setServiceProperties(serviceProperties); + return entryPoint; + } + + + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 2c88b74a83..16254c8cbd 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; @@ -13,24 +13,27 @@ import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; + @Controller public class AuthController { - private Logger logger = LogManager.getLogger(AuthController.class); - - @GetMapping("/logout") - public String logout( - HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - logoutHandler.logout(request, response, auth ); - new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY).logout(request, response, auth); - return "auth/logout"; - } - + private Logger logger = LoggerFactory.getLogger(AuthController.class); @GetMapping("/login") public String login() { + logger.info("/login called"); return "redirect:/secured"; } + + @GetMapping("/logout") + public String logout(HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + cookieClearingLogoutHandler.logout(request, response, auth); + logoutHandler.logout(request, response, auth); + return "auth/logout"; + } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java index 75956cf493..d4800206d4 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java @@ -1,15 +1,19 @@ package com.baeldung.cassecuredapp.controllers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - @Controller public class IndexController { + private Logger logger = LoggerFactory.getLogger(IndexController.class); + @GetMapping("/") public String index() { + logger.info("Index controller called"); return "index"; } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java new file mode 100644 index 0000000000..0b3ab6199f --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java @@ -0,0 +1,30 @@ +package com.baeldung.cassecuredapp.controllers; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SecuredController { + + private Logger logger = LoggerFactory.getLogger(SecuredController.class); + + @GetMapping("/secured") + public String securedIndex(ModelMap modelMap) { + + logger.info("/secured called"); + + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + + if(auth.getPrincipal() instanceof UserDetails) + modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); + + return "secure/index"; + } +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java deleted file mode 100644 index 9a872d1f40..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.cassecuredapp.controllers; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/secured") -public class SecuredPageController { - - @GetMapping - public String index(ModelMap modelMap) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if( auth != null && auth.getPrincipal() != null - && auth.getPrincipal() instanceof UserDetails) { - modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); - } - return "secure/index"; - } -} diff --git a/cas/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties index 99802c632f..f8789997d5 100644 --- a/cas/cas-secured-app/src/main/resources/application.properties +++ b/cas/cas-secured-app/src/main/resources/application.properties @@ -1 +1,2 @@ -server.port=9000 \ No newline at end of file +server.port=8900 +spring.freemarker.suffix=.ftl \ No newline at end of file diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java index 2f2644e2ea..de13f6665d 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationIntegrationTest { +public class CasSecuredApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath deleted file mode 100644 index 006c761796..0000000000 --- a/cas/cas-server/.factorypath +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/.gitignore b/cas/cas-server/.gitignore old mode 100644 new mode 100755 index 5304519922..6121b5ea9d --- a/cas/cas-server/.gitignore +++ b/cas/cas-server/.gitignore @@ -2,6 +2,8 @@ !/.project .project .settings +.history +.vscode target/ .idea/ .DS_Store @@ -9,6 +11,11 @@ target/ overlays/ .gradle/ build/ +log/ bin/ +*.war *.iml *.log +tmp/ +./apache-tomcat +apache-tomcat.zip \ No newline at end of file diff --git a/cas/cas-server/.mergify.yml b/cas/cas-server/.mergify.yml new file mode 100644 index 0000000000..4fcbdbe4ac --- /dev/null +++ b/cas/cas-server/.mergify.yml @@ -0,0 +1,32 @@ +# +# Licensed to Apereo under one or more contributor license +# agreements. See the NOTICE file distributed with this work +# for additional information regarding copyright ownership. +# Apereo licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a +# copy of the License at the following location: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +pull_request_rules: +- name: automatic merge by dependabot + conditions: + - status-success=continuous-integration/travis-ci/pr + - status-success=WIP + - "#changes-requested-reviews-by=0" + - base=master + - label=dependencies + actions: + merge: + method: merge + strict: true + delete_head_branch: \ No newline at end of file diff --git a/cas/cas-server/.travis.yml b/cas/cas-server/.travis.yml new file mode 100644 index 0000000000..8347dd1719 --- /dev/null +++ b/cas/cas-server/.travis.yml @@ -0,0 +1,62 @@ +language: java +sudo: required +dist: trusty +services: + - docker +branches: + only: + - master +before_cache: + - rm -rf $HOME/.gradle/caches/5.*/ + - rm -rf $HOME/.gradle/caches/4.*/ + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + - find ~/.gradle/caches/ -name "*.lock" -type f -delete +cache: + bundler: false + cargo: false + directories: + - $HOME/.m2 + - $HOME/.npm/ + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ +env: + global: + - JAVA_OPTS="-Xms512m -Xmx4048m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" + - GRADLE_OPTS="-Xms512m -Xmx1024m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" +jdk: +- openjdk11 +before_install: +- echo -e "Configuring Gradle wrapper...\n" +- mkdir -p ~/.gradle && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties +- chmod -R 777 ./gradlew +- chmod -R 777 *.sh +install: true +stages: + - build + - validate + - docker +jobs: + include: + - stage: build + script: ./gradlew clean build --stacktrace --no-daemon --refresh-dependencies -Dorg.gradle.internal.http.socketTimeout=600000 -Dorg.gradle.internal.http.connectionTimeout=600000 + name: "Build CAS" + ############################################ + - stage: validate + script: ./gradlew downloadShell + name: "Download CAS Shell" + - stage: validate + script: ./gradlew listTemplateViews + name: "List CAS Template Views" + - stage: validate + script: ./gradlew explodeWar + name: "Unzip CAS Web Application" + ############################################ + - stage: docker + script: ./gradlew build jibDockerBuild --stacktrace --no-daemon --refresh-dependencies + name: "Build Docker Image via Jib" + - stage: docker + script: docker-compose build + name: "Build Docker Image via Docker Compose" + - stage: docker + script: ./docker-build.sh + name: "Build Docker Image" \ No newline at end of file diff --git a/cas/cas-server/Dockerfile b/cas/cas-server/Dockerfile new file mode 100644 index 0000000000..b2f15ef4c3 --- /dev/null +++ b/cas/cas-server/Dockerfile @@ -0,0 +1,40 @@ +FROM adoptopenjdk/openjdk11:alpine-slim AS overlay + +RUN mkdir -p cas-overlay +COPY ./src cas-overlay/src/ +COPY ./gradle/ cas-overlay/gradle/ +COPY ./gradlew ./settings.gradle ./build.gradle ./gradle.properties /cas-overlay/ + +RUN mkdir -p ~/.gradle \ + && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties \ + && echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties \ + && cd cas-overlay \ + && chmod 750 ./gradlew \ + && ./gradlew --version; + +RUN cd cas-overlay \ + && ./gradlew clean build --parallel; + +FROM adoptopenjdk/openjdk11:alpine-jre AS cas + +LABEL "Organization"="Apereo" +LABEL "Description"="Apereo CAS" + +RUN cd / \ + && mkdir -p /etc/cas/config \ + && mkdir -p /etc/cas/services \ + && mkdir -p /etc/cas/saml \ + && mkdir -p cas-overlay; + +COPY etc/cas/ /etc/cas/ +COPY etc/cas/config/ /etc/cas/config/ +COPY etc/cas/services/ /etc/cas/services/ +COPY etc/cas/saml/ /etc/cas/saml/ +COPY --from=overlay cas-overlay/build/libs/cas.war cas-overlay/ + +EXPOSE 8080 8443 + +ENV PATH $PATH:$JAVA_HOME/bin:. + +WORKDIR cas-overlay +ENTRYPOINT ["java", "-server", "-noverify", "-Xmx2048M", "-jar", "cas.war"] diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index 44cfa2246c..b224738732 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -1,105 +1,146 @@ -CAS Overlay Template -============================ +CAS Overlay Template [![Build Status](https://travis-ci.org/apereo/cas-overlay-template.svg?branch=master)](https://travis-ci.org/apereo/cas-overlay-template) +======================= -Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. The CAS services management overlay is available [here](https://github.com/apereo/cas-services-management-overlay). +Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. # Versions -```xml -5.3.x +- CAS `6.1.x` +- JDK `11` + +# Overview + +To build the project, use: + +```bash +# Use --refresh-dependencies to force-update SNAPSHOT versions +./gradlew[.bat] clean build ``` -# Requirements - -* JDK 1.8+ - -# Configuration - -The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. - -# Build - To see what commands are available to the build script, run: ```bash -./build.sh help +./gradlew[.bat] tasks ``` -To package the final web application, run: +To launch into the CAS command-line shell: ```bash -./build.sh package +./gradlew[.bat] downloadShell runShell ``` -To update `SNAPSHOT` versions run: +To fetch and overlay a CAS resource or view, use: ```bash -./build.sh package -U +./gradlew[.bat] getResource -PresourceName=[resource-name] ``` +To list all available CAS views and templates: + +```bash +./gradlew[.bat] listTemplateViews +``` + +To unzip and explode the CAS web application file and the internal resources jar: + +```bash +./gradlew[.bat] explodeWar +``` + +# Configuration + +- The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. + +```bash +./gradlew[.bat] copyCasConfiguration +``` + +- The specifics of the build are controlled using the `gradle.properties` file. + +## Adding Modules + +CAS modules may be specified under the `dependencies` block of the [Gradle build script](build.gradle): + +```gradle +dependencies { + compile "org.apereo.cas:cas-server-some-module:${project.casVersion}" + ... +} +``` + +To collect the list of all project modules and dependencies: + +```bash +./gradlew[.bat] allDependencies +``` + +### Clear Gradle Cache + +If you need to, on Linux/Unix systems, you can delete all the existing artifacts (artifacts and metadata) Gradle has downloaded using: + +```bash +# Only do this when absolutely necessary +rm -rf $HOME/.gradle/caches/ +``` + +Same strategy applies to Windows too, provided you switch `$HOME` to its equivalent in the above command. + # Deployment -- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. +- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. This can either be done using the JDK's `keytool` utility or via the following command: + +```bash +./gradlew[.bat] createKeystore +``` + - Ensure the keystore is loaded up with keys and certificates of the server. On a successful deployment via the following methods, CAS will be available at: -* `http://cas.server.name:8080/cas` * `https://cas.server.name:8443/cas` ## Executable WAR -Run the CAS web application as an executable WAR. +Run the CAS web application as an executable WAR: ```bash -./build.sh run +./gradlew[.bat] run ``` -## Spring Boot - -Run the CAS web application as an executable WAR via Spring Boot. This is most useful during development and testing. +Debug the CAS web application as an executable WAR: ```bash -./build.sh bootrun +./gradlew[.bat] debug ``` -### Warning! +Run the CAS web application as a *standalone* executable WAR: -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. - - -## Spring Boot App Server Selection - -There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. -It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. - -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. - -```xml --tomcat -``` - -## Windows Build - -If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: - -``` -build.cmd help +```bash +./gradlew[.bat] clean executable ``` ## External -Deploy resultant `target/cas.war` to a servlet container of choice. +Deploy the binary web application file `cas.war` after a successful build to a servlet container of choice. +## Docker -## Command Line Shell +The following strategies outline how to build and deploy CAS Docker images. -Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. +### Jib + +The overlay embraces the [Jib Gradle Plugin](https://github.com/GoogleContainerTools/jib) to provide easy-to-use out-of-the-box tooling for building CAS docker images. Jib is an open-source Java containerizer from Google that lets Java developers build containers using the tools they know. It is a container image builder that handles all the steps of packaging your application into a container image. It does not require you to write a Dockerfile or have Docker installed, and it is directly integrated into the overlay. ```bash -./build.sh cli +./gradlew build jibDockerBuild ``` -### Relevant Articles: +### Dockerfile -- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) +You can also use the native Docker tooling and the provided `Dockerfile` to build and run CAS. + +```bash +chmod +x *.sh +./docker-build.sh +./docker-run.sh +``` diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd deleted file mode 100644 index 2cf9262afe..0000000000 --- a/cas/cas-server/build.cmd +++ /dev/null @@ -1,102 +0,0 @@ -@echo off - -@set JAVA_ARGS=-Xms500m -Xmx1g -@set CAS_DIR=\etc\cas -@set CONFIG_DIR=\etc\cas\config - -@rem Call this script with DNAME and CERT_SUBJ_ALT_NAMES already set to override -@if "%DNAME%" == "" set DNAME=CN=cas.example.org,OU=Example,OU=Org,C=US -@rem List other host names or ip addresses you want in your certificate, may help with host name verification, -@rem if client apps make https connection for ticket validation and compare name in cert (include sub. alt. names) -@rem to name used to access CAS -@if "%CERT_SUBJ_ALT_NAMES%" == "" set CERT_SUBJ_ALT_NAMES=dns:example.org,dns:localhost,dns:%COMPUTERNAME%,ip:127.0.0.1 - -@rem Check for mvn in path, use it if found, otherwise use maven wrapper -@set MAVEN_CMD=mvn -@where /q mvn -@if %ERRORLEVEL% neq 0 set MAVEN_CMD=.\mvnw.bat - -@if "%1" == "" call:help -@if "%1" == "copy" call:copy -@if "%1" == "clean" call:clean %2 %3 %4 -@if "%1" == "package" call:package %2 %3 %4 -@if "%1" == "bootrun" call:bootrun %2 %3 %4 -@if "%1" == "debug" call:debug %2 %3 %4 -@if "%1" == "run" call:run %2 %3 %4 -@if "%1" == "runalone" call:runalone %2 %3 %4 -@if "%1" == "help" call:help -@if "%1" == "gencert" call:gencert -@if "%1" == "cli" call:runcli %2 %3 %4 - -@rem function section starts here -@goto:eof - -:copy - @echo "Creating configuration directory under %CONFIG_DIR%" - if not exist %CONFIG_DIR% mkdir %CONFIG_DIR% - - @echo "Copying configuration files from etc/cas to /etc/cas" - xcopy /S /Y etc\cas\* \etc\cas -@goto:eof - -:help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" - @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" - @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" -@goto:eof - -:clean - call %MAVEN_CMD% clean %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:package - call %MAVEN_CMD% clean package -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:bootrun - call %MAVEN_CMD% clean package spring-boot:run -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:debug - call:package %1 %2 %3 & java %JAVA_ARGS% -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -@goto:eof - -:run - call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war -@goto:eof - -:runalone - call:package %1 %2 %3 & target/cas.war -@goto:eof - -:gencert - where /q keytool - if ERRORLEVEL 1 ( - @echo Java keytool.exe not found in path. - exit /b 1 - ) else ( - if not exist %CAS_DIR% mkdir %CAS_DIR% - @echo on - @echo Generating self-signed SSL cert for %DNAME% in %CAS_DIR%\thekeystore - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore %CAS_DIR%\thekeystore -dname %DNAME% -ext SAN=%CERT_SUBJ_ALT_NAMES% - @echo Exporting cert for use in trust store (used by cas clients) - keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer - ) -@goto:eof - -:runcli - for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i - @set CAS_VERSION=%CAS_VERSION: =% - @set DOWNLOAD_DIR=target - @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar - @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% - @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% - ) - @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 - -@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.gradle b/cas/cas-server/build.gradle new file mode 100644 index 0000000000..41381e2d8f --- /dev/null +++ b/cas/cas-server/build.gradle @@ -0,0 +1,106 @@ +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://repo.spring.io/libs-milestone" } + maven { url "https://repo.spring.io/libs-snapshot" } + maven { url "https://plugins.gradle.org/m2/" } + } + dependencies { + classpath "de.undercouch:gradle-download-task:${project.gradleDownloadTaskVersion}" + classpath "org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}" + classpath "gradle.plugin.com.google.cloud.tools:jib-gradle-plugin:${project.jibVersion}" + classpath "io.freefair.gradle:maven-plugin:${project.gradleMavenPluginVersion}" + } +} + +repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" } + maven { url "https://repo.spring.io/milestone/" } + maven { url "https://repo.spring.io/snapshot/" } + maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } +} + +def casServerVersion = project.'cas.version' +def casWebApplicationBinaryName = "cas.war" + +project.ext."casServerVersion" = casServerVersion +project.ext."casWebApplicationBinaryName" = casWebApplicationBinaryName + +apply plugin: "io.freefair.war-overlay" +apply from: rootProject.file("gradle/tasks.gradle") + +apply plugin: "war" +apply plugin: "eclipse" +apply plugin: "idea" + +apply from: rootProject.file("gradle/springboot.gradle") +apply from: rootProject.file("gradle/dockerjib.gradle") + +dependencies { + // Other CAS dependencies/modules may be listed here... + compile "org.apereo.cas:cas-server-support-json-service-registry:${casServerVersion}" + compile "org.apereo.cas:cas-server-support-jdbc:${casServerVersion}" +} + +tasks.findByName("jibDockerBuild") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +tasks.findByName("jib") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +configurations.all { + resolutionStrategy { + cacheChangingModulesFor 0, "seconds" + cacheDynamicVersionsFor 0, "seconds" + + preferProjectModules() + + def failIfConflict = project.hasProperty("failOnVersionConflict") && Boolean.valueOf(project.getProperty("failOnVersionConflict")) + if (failIfConflict) { + failOnVersionConflict() + } + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} + +bootWar { + entryCompression = ZipEntryCompression.STORED + overlays { + // https://docs.freefair.io/gradle-plugins/current/reference/#_io_freefair_war_overlay + // Note: The "excludes" property is only for files in the war dependency. + // If a jar is excluded from the war, it could be brought back into the final war as a dependency + // of non-war dependencies. Those should be excluded via normal gradle dependency exclusions. + cas { + from "org.apereo.cas:cas-server-webapp${project.appServer}:${casServerVersion}@war" + provided = false + //excludes = ["WEB-INF/lib/somejar-1.0*"] + } + } +} + + +wrapper { + distributionType = Wrapper.DistributionType.BIN + gradleVersion = "${project.gradleVersion}" +} diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh deleted file mode 100644 index 4d80aa2593..0000000000 --- a/cas/cas-server/build.sh +++ /dev/null @@ -1,189 +0,0 @@ -#!/bin/bash - - -function copy() { - echo -e "Creating configuration directory under /etc/cas" - mkdir -p /etc/cas/config - - echo -e "Copying configuration files from etc/cas to /etc/cas" - cp -rfv etc/cas/* /etc/cas -} - -function help() { - echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" - echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" - echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war" - echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" - echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" - echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin" - echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" - echo " getview: Ask for a view name to be included in the overlay for customizations" - echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" - echo " cli: Run the CAS command line shell and pass commands" -} - -function clean() { - shift - ./mvnw clean "$@" -} - -function package() { - shift - ./mvnw clean package -T 5 "$@" - # copy -} - -function bootrun() { - shift - ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" -} - -function debug() { - package && java -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -} - -function run() { - package && java -jar target/cas.war -} - -function runalone() { - shift - ./mvnw clean package -P default,exec "$@" - chmod +x target/cas.war - target/cas.war -} - -function listviews() { - shift - explodeapp - find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more -} - -function explodeapp() { - if [ ! -d $PWD/target/cas ];then - echo "Building the CAS web application and exploding the final war file..." - ./mvnw clean package war:exploded "$@" - fi - echo "Exploded the CAS web application file." -} - -function getview() { - shift - explodeapp - echo "Searching for view name $@..." - results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` - echo -e "Found view(s): \n$results" - count=`wc -w <<< "$results"` - if [ "$count" -eq 1 ];then - # echo "Found view $results to include in the overlay" - firststring="target/cas/WEB-INF/classes" - secondstring="src/main/resources" - overlayfile=`echo "${results/$firststring/$secondstring}"` - overlaypath=`dirname "${overlayfile}"` - # echo "Overlay file is $overlayfile to be created at $overlaypath" - mkdir -p $overlaypath - cp $results $overlaypath - echo "Created view at $overlayfile" - ls $overlayfile - else - echo "More than one view file is found. Narrow down the search query..." - fi -} - - -function gencert() { - if [[ ! -d /etc/cas ]] ; then - copy - fi - which keytool - if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 - fi - # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values - DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" - CERT_SUBJ_ALT_NAMES="${CERT_SUBJ_ALT_NAMES:-dns:example.org,dns:localhost,ip:127.0.0.1}" - echo "Generating keystore for CAS with DN ${DNAME}" - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore /etc/cas/thekeystore -dname ${DNAME} -ext SAN=${CERT_SUBJ_ALT_NAMES} - keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer -} - -function cli() { - - CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) - # echo "CAS version: $CAS_VERSION" - JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" - # echo "JAR name: $JAR_FILE_NAME" - JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" - # echo "JAR path: $JAR_PATH" - - JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; - # echo "Local JAR file path: $JAR_FILE_LOCAL"; - if [ -f "$JAR_FILE_LOCAL" ]; then - # echo "Using JAR file locally at $JAR_FILE_LOCAL" - java -jar $JAR_FILE_LOCAL "$@" - exit 0; - fi - - DOWNLOAD_DIR=./target - COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" - if [ ! -f "$COMMAND_FILE" ]; then - mkdir -p $DOWNLOAD_DIR - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR - fi - java -jar $COMMAND_FILE "$@" - exit 0; - -} - -if [ $# -eq 0 ]; then - echo -e "No commands provided. Defaulting to [run]\n" - run - exit 0 -fi - -case "$1" in -"copy") - copy - ;; -"clean") - shift - clean "$@" - ;; -"package") - shift - package "$@" - ;; -"bootrun") - shift - bootrun "$@" - ;; -"debug") - debug "$@" - ;; -"run") - run "$@" - ;; -"runalone") - runalone "$@" - ;; -"listviews") - listviews "$@" - ;; -"gencert") - gencert "$@" - ;; -"getview") - getview "$@" - ;; -"cli") - shift - cli "$@" - ;; -*) - help - ;; -esac diff --git a/cas/cas-server/docker-build.sh b/cas/cas-server/docker-build.sh new file mode 100755 index 0000000000..8f2c2776bf --- /dev/null +++ b/cas/cas-server/docker-build.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Building CAS docker image tagged as [$image_tag]" +# read -p "Press [Enter] to continue..." any_key; + +docker build --tag="org.apereo.cas/cas:$image_tag" . \ + && echo "Built CAS image successfully tagged as org.apereo.cas/cas:$image_tag" \ + && docker images "org.apereo.cas/cas:$image_tag" \ No newline at end of file diff --git a/cas/cas-server/docker-compose.yml b/cas/cas-server/docker-compose.yml new file mode 100644 index 0000000000..8f2e6ca7c9 --- /dev/null +++ b/cas/cas-server/docker-compose.yml @@ -0,0 +1,7 @@ +version: '3' +services: + cas: + build: . + ports: + - "8443:8443" + - "8080:8080" \ No newline at end of file diff --git a/cas/cas-server/docker-push.sh b/cas/cas-server/docker-push.sh new file mode 100755 index 0000000000..e04b107212 --- /dev/null +++ b/cas/cas-server/docker-push.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +read -p "Docker username: " docker_user +read -s -p "Docker password: " docker_psw + +echo "$docker_psw" | docker login --username "$docker_user" --password-stdin + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Pushing CAS docker image tagged as $image_tag to org.apereo.cas/cas..." +docker push org.apereo.cas/cas:"$image_tag" \ + && echo "Pushed org.apereo.cas/cas:$image_tag successfully."; \ No newline at end of file diff --git a/cas/cas-server/docker-run.sh b/cas/cas-server/docker-run.sh new file mode 100755 index 0000000000..f8627859f2 --- /dev/null +++ b/cas/cas-server/docker-run.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +docker stop cas > /dev/null 2>&1 +docker rm cas > /dev/null 2>&1 +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) +docker run -d -p 8080:8080 -p 8443:8443 --name="cas" org.apereo.cas/cas:"${image_tag}" +docker logs -f cas \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties index 47a1477308..a3be0e1388 100644 --- a/cas/cas-server/etc/cas/config/cas.properties +++ b/cas/cas-server/etc/cas/config/cas.properties @@ -1,7 +1,6 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 +cas.server.name=https://cas.example.org:8443 +cas.server.prefix=${cas.server.name}/cas logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services + +# cas.authn.accept.users= diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index e688cc0350..685dfab245 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -2,20 +2,26 @@ - - . - - warn + /var/log + + info + warn + info + warn + debug + warn + warn + warn + warn + warn + warn - + - + @@ -23,8 +29,8 @@ - + @@ -33,16 +39,6 @@ - - - - - - - - - @@ -52,52 +48,58 @@ - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/etc/cas/saml/.gitkeep b/cas/cas-server/etc/cas/saml/.gitkeep new file mode 100644 index 0000000000..882c99944d --- /dev/null +++ b/cas/cas-server/etc/cas/saml/.gitkeep @@ -0,0 +1 @@ +This directory is references in the Dockerfile so it needs to be here. \ No newline at end of file diff --git a/cas/cas-server/etc/cas/services/.donotdel b/cas/cas-server/etc/cas/services/.donotdel new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cas/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore new file mode 100644 index 0000000000..78f49baf74 Binary files /dev/null and b/cas/cas-server/etc/cas/thekeystore differ diff --git a/cas/cas-server/gradle.properties b/cas/cas-server/gradle.properties new file mode 100644 index 0000000000..28daacc245 --- /dev/null +++ b/cas/cas-server/gradle.properties @@ -0,0 +1,28 @@ +# Versions +cas.version=6.1.5 +springBootVersion=2.2.0.RELEASE + +# Use -jetty, -undertow to other containers +# Or blank if you want to deploy to an external container +appServer=-tomcat +executable=false + +gradleVersion=5.6.3 +tomcatVersion=9.0.30 + +group=org.apereo.cas +sourceCompatibility=11 +targetCompatibility=11 + +jibVersion=1.7.0 + +# Location of the downloaded CAS shell JAR +shellDir=build/libs +ivyVersion=2.4.0 +gradleDownloadTaskVersion=3.4.3 +gradleMavenPluginVersion=3.8.4 + +# use without "-slim" in tag name if you want tools like jstack, adds about 100MB to image size +# (https://hub.docker.com/r/adoptopenjdk/openjdk11/tags/) +baseDockerImage=adoptopenjdk/openjdk11:alpine-jre +allowInsecureRegistries=false diff --git a/cas/cas-server/gradle/dockerjib.gradle b/cas/cas-server/gradle/dockerjib.gradle new file mode 100644 index 0000000000..dcd70e3875 --- /dev/null +++ b/cas/cas-server/gradle/dockerjib.gradle @@ -0,0 +1,52 @@ +apply plugin: "com.google.cloud.tools.jib" + +jib { + from { + image = project.baseDockerImage + } + to { + image = "${project.group}/${project.name}" + /** + ecr-login: Amazon Elastic Container Registry (ECR) + gcr: Google Container Registry (GCR) + osxkeychain: Docker Hub + */ + credHelper = "osxkeychain" + /** + auth { + username = "*******" + password = "*******" + } + tags = [casServerVersion] + */ + } + container { + useCurrentTimestamp = true + entrypoint = ['docker/entrypoint.sh'] + ports = ['80', '443', '8080', '8443'] + labels = [version:casServerVersion, name:project.name, group:project.group] + } + extraDirectories { + paths = 'src/main/jib' + permissions = [ + '/docker/entrypoint.sh': '755' + ] + } + allowInsecureRegistries = project.allowInsecureRegistries +} + +task copyWebAppIntoJib(type: Copy, group: "Docker", description: "Copy the web application into Docker image") { + dependsOn build + from "build/libs/${casWebApplicationBinaryName}" + into "src/main/jib/docker/cas/war" +} + +task copyConfigIntoJib(type: Copy, group: "Docker", description: "Copy the CAS configuration into Docker image") { + dependsOn build + from "etc/cas" + into "src/main/jib/docker/cas" +} + +task deleteWebAppFromJib(type: Delete, group: "Docker", description: "Explodes the CAS web application archive") { + delete "src/main/jib/docker/cas" +} \ No newline at end of file diff --git a/cas/cas-server/gradle/springboot.gradle b/cas/cas-server/gradle/springboot.gradle new file mode 100644 index 0000000000..b6a46b8940 --- /dev/null +++ b/cas/cas-server/gradle/springboot.gradle @@ -0,0 +1,24 @@ +apply plugin: "org.springframework.boot" + +bootRun.enabled = false +bootRun.onlyIf { return false } +tasks.remove(tasks['bootRun']) + +springBoot { + mainClassName = "org.apereo.cas.web.CasWebApplication" +} + +bootWar { + doFirst { + def executable = project.hasProperty("executable") && Boolean.valueOf(project.getProperty("executable")) + if (executable) { + logger.info "Including launch script for executable WAR artifact" + launchScript() + } else { + logger.info "WAR artifact is not marked as an executable" + } + archiveName "${casWebApplicationBinaryName}" + baseName "cas" + excludeDevtools = true + } +} \ No newline at end of file diff --git a/cas/cas-server/gradle/tasks.gradle b/cas/cas-server/gradle/tasks.gradle new file mode 100644 index 0000000000..2babeb2d1f --- /dev/null +++ b/cas/cas-server/gradle/tasks.gradle @@ -0,0 +1,258 @@ +import org.apache.ivy.util.url.* +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.api.tasks.Copy + +import java.nio.file.* +import org.gradle.internal.logging.text.StyledTextOutputFactory; +import static org.gradle.internal.logging.text.StyledTextOutput.Style; + +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + } + dependencies { + classpath "org.apache.ivy:ivy:${project.ivyVersion}" + } +} + +apply plugin: "de.undercouch.download" + +def tomcatDirectory = "${buildDir}/apache-tomcat-${tomcatVersion}" +project.ext."tomcatDirectory" = tomcatDirectory + +def explodedDir="${buildDir}/cas" +def explodedResourcesDir="${buildDir}/cas-resources" +def resourceJarName = "cas-server-webapp-resources" + +task copyCasConfiguration(type: Copy, group: "build", description: "Copy the CAS configuration from this project to /etc/cas/config") { + from "etc/cas/config" + into new File('/etc/cas/config').absolutePath + doFirst { + new File('/etc/cas/config').mkdirs() + } +} + +task explodeWarOnly(type: Copy, group: "build", description: "Explodes the CAS web application archive") { + dependsOn 'build' + from zipTree("build/libs/${casWebApplicationBinaryName}") + into explodedDir +} + +task explodeWar(type: Copy, group: "build", description: "Explodes the CAS archive and resources jar from the CAS web application archive") { + dependsOn explodeWarOnly + from zipTree("${explodedDir}/WEB-INF/lib/${resourceJarName}-${casServerVersion}.jar") + into explodedResourcesDir +} + +task run(group: "build", description: "Run the CAS web application in embedded container mode") { + dependsOn 'build' + doLast { + def casRunArgs = new ArrayList<>(Arrays.asList("-server -noverify -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1".split(" "))) + if (project.hasProperty('args')) { + casRunArgs.addAll(project.args.split('\\s+')) + } + javaexec { + main = "-jar" + jvmArgs = casRunArgs + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task setExecutable(group: "build", description: "Configure the project to run in executable mode") { + doFirst { + project.setProperty("executable", "true") + logger.info "Configuring the project as executable" + } +} + +task executable(type:Exec, group: "build", description: "Run the CAS web application in standalone executable mode") { + dependsOn setExecutable, 'build' + doFirst { + workingDir "." + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + commandLine "chmod", "+x", bootWar.archivePath + } + logger.info "Running ${bootWar.archivePath}" + commandLine bootWar.archivePath + } +} + +task debug(group: "build", description: "Debug the CAS web application in embedded mode on port 5005") { + dependsOn 'build' + doLast { + logger.info "Debugging process is started in a suspended state, listening on port 5005." + def casArgs = Arrays.asList("-Xmx2048M".split(" ")) + javaexec { + main = "-jar" + jvmArgs = casArgs + debug = true + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task downloadShell(group: "shell", description: "Download CAS shell jar from snapshot or release maven repo") { + doFirst { + mkdir "${project.shellDir}" + } + doLast { + def downloadFile + if (isRunningCasServerSnapshot(casServerVersion)) { + def snapshotDir = "https://oss.sonatype.org/content/repositories/snapshots/org/apereo/cas/cas-server-support-shell/${casServerVersion}/" + def files = new ApacheURLLister().listFiles(new URL(snapshotDir)) + files = files.sort{it.path} + files.each { + if (it.path.endsWith(".jar")) { + downloadFile = it + } + } + } else { + downloadFile = "https://repo1.maven.org/maven2/org/apereo/cas/cas-server-support-shell/${casServerVersion}/cas-server-support-shell-${casServerVersion}.jar" + } + logger.info "Downloading file: ${downloadFile}" + download { + src downloadFile + dest new File("${project.shellDir}", "cas-server-support-shell-${casServerVersion}.jar") + overwrite false + } + } +} + +task runShell(group: "shell", description: "Run the CAS shell") { + dependsOn downloadShell + doLast { + println "Run the following command to launch the shell:\n\tjava -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar" + } +} + +task debugShell(group: "shell", description: "Run the CAS shell with debug options, wait for debugger on port 5005") { + dependsOn downloadShell + doLast { + println """ + Run the following command to launch the shell:\n\t + java -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=y -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar + """ + } +} + +task showConfiguration(group: "build", description: "Show configurations for each dependency, etc") { + doLast() { + def cfg = project.hasProperty("configuration") ? project.property("configuration") : "compile" + configurations.getByName(cfg).each { println it } + } +} + +task allDependenciesInsight(group: "build", type: DependencyInsightReportTask, description: "Produce insight information for all dependencies") {} + +task allDependencies(group: "build", type: DependencyReportTask, description: "Display a graph of all project dependencies") {} + +task casVersion (group: "build", description: "Display the current CAS version") { + doFirst { + def verbose = project.hasProperty("verbose") && Boolean.valueOf(project.getProperty("verbose")) + if (verbose) { + def out = services.get(StyledTextOutputFactory).create("CAS") + println "******************************************************************" + out.withStyle(Style.Info).println "Apereo CAS $casServerVersion" + out.withStyle(Style.Description).println "Enterprise Single SignOn for all earthlings and beyond" + out.withStyle(Style.SuccessHeader).println "- GitHub: " + out.withStyle(Style.Success).println "https://github.com/apereo/cas" + out.withStyle(Style.SuccessHeader).println "- Docs: " + out.withStyle(Style.Success).println "https://apereo.github.io/cas" + out.withStyle(Style.SuccessHeader).println "- Blog: " + out.withStyle(Style.Success).println "https://apereo.github.io" + println "******************************************************************" + } else { + println casServerVersion + } + } +} + +task createKeystore(group: "build", description: "Create CAS keystore") { + doFirst { + mkdir "/etc/cas" + + def keystorePath = "/etc/cas/thekeystore" + + def dn = "CN=cas.example.org,OU=Example,OU=Org,C=US" + if (project.hasProperty("certificateDn")) { + dn = project.getProperty("certificateDn") + } + def subjectAltName = "dns:example.org,dns:localhost,ip:127.0.0.1" + if (project.hasProperty("certificateSubAltName")) { + subjectAltName = project.getProperty("certificateSubAltName") + } + // this will fail if thekeystore exists and has cert with cas alias already (so delete if you want to recreate) + logger.info "Generating keystore for CAS with DN ${dn}" + exec { + workingDir "." + commandLine "keytool", "-genkeypair", "-alias", "cas", + "-keyalg", "RSA", + "-keypass", "changeit", "-storepass", "changeit", + "-keystore", keystorePath, + "-dname", dn, "-ext", "SAN=${subjectAltName}" + } + logger.info "Exporting cert from keystore..." + exec { + workingDir "." + commandLine "keytool", "-exportcert", "-alias", "cas", + "-storepass", "changeit", "-keystore", keystorePath, + "-file", "/etc/cas/cas.cer" + } + logger.info "Import /etc/cas/cas.cer into your Java truststore (JAVA_HOME/lib/security/cacerts)" + } +} + +task listTemplateViews (group: "build", description: "List all CAS views") { + dependsOn explodeWar + + doFirst { + fileTree(explodedResourcesDir).matching { + include "**/*.html" + } + .collect { it.name } + .toSorted() + .each { println it } + } +} + +task getResource(group: "build", description: "Fetch a CAS resource and move it into the overlay") { + dependsOn explodeWar + + doFirst { + def resourceName = project.getProperty("resourceName") + + def results = fileTree(explodedResourcesDir).matching { + include "**/${resourceName}.*" + } + if (results.isEmpty()) { + println "No resources could be found matching ${resourceName}" + return + } + if (results.size() > 1) { + println "Multiple resources found matching ${resourceName}: ${results}" + return + } + + def fromFile = explodedResourcesDir + def resourcesDir = "src/main/resources" + mkdir resourcesDir + + def resourceFile = results[0].canonicalPath + def toResourceFile = resourceFile.replace(fromFile, resourcesDir) + + def parent = file(toResourceFile).getParent() + mkdir parent + + Files.copy(Paths.get(resourceFile), Paths.get(toResourceFile), StandardCopyOption.REPLACE_EXISTING) + println "Copied file ${resourceFile} to ${toResourceFile}" + } +} + +def isRunningCasServerSnapshot(casServerVersion) { + return "${casServerVersion}".contains("-SNAPSHOT") +} \ No newline at end of file diff --git a/cas/cas-server/gradle/wrapper/gradle-wrapper.properties b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..f04d6a20ae --- /dev/null +++ b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/cas/cas-server/gradlew b/cas/cas-server/gradlew new file mode 100755 index 0000000000..83f2acfdc3 --- /dev/null +++ b/cas/cas-server/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/cas/cas-server/gradlew.bat b/cas/cas-server/gradlew.bat new file mode 100644 index 0000000000..24467a141f --- /dev/null +++ b/cas/cas-server/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar deleted file mode 100644 index 18ba302c65..0000000000 Binary files a/cas/cas-server/maven/maven-wrapper.jar and /dev/null differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties deleted file mode 100644 index 97a946225a..0000000000 --- a/cas/cas-server/maven/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -#Maven download properties -#Fri Dec 01 21:35:11 MST 2017 -distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/cas/cas-server/mvnw b/cas/cas-server/mvnw deleted file mode 100644 index 2275ac7647..0000000000 --- a/cas/cas-server/mvnw +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - wdir=$(cd "$wdir/.."; pwd) - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER="org.apache.maven.wrapper.MavenWrapperMain" - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - -classpath \ -"$MAVEN_PROJECTBASEDIR/maven/maven-wrapper.jar" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/cas/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat deleted file mode 100644 index d391151aa7..0000000000 --- a/cas/cas-server/mvnw.bat +++ /dev/null @@ -1,174 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:chkMHome -if not "%M2_HOME%"=="" goto valMHome - -SET "M2_HOME=%~dp0.." -if not "%M2_HOME%"=="" goto valMHome - -echo. -echo Error: M2_HOME not found in your environment. >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation. >&2 -echo. -goto error - -:valMHome - -:stripMHome -if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd -set "M2_HOME=%M2_HOME:~0,-1%" -goto stripMHome - -:checkMCmd -if exist "%M2_HOME%\bin\mvn.cmd" goto init - -echo. -echo Error: M2_HOME is set to an invalid directory. >&2 -echo M2_HOME = "%M2_HOME%" >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation >&2 -echo. -goto error -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\maven\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index abcf251667..e69de29bb2 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -1,208 +0,0 @@ - - - 4.0.0 - cas-server - 1.0 - cas-server - war - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - - - - - - - com.rimerosolutions.maven.plugins - wrapper-maven-plugin - ${wrapper-maven-plugin.version} - - true - MD5 - - - - org.springframework.boot - spring-boot-maven-plugin - - ${mainClassName} - true - ${isExecutable} - WAR - - - - - repackage - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - cas - false - false - - false - ${manifestFileToUse} - - - - org.apereo.cas - cas-server-webapp${app.server} - - - - - - cas - - - - - - true - - default - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - - false - - exec - - org.apereo.cas.web.CasWebApplication - true - - - - - - com.soebes.maven.plugins - echo-maven-plugin - ${echo-maven-plugin.version} - - - prepare-package - - echo - - - - - - Executable profile to make the generated CAS web application executable. - - - - - - - - - - false - - bootiful - - -tomcat - false - - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - false - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - - - - 5.3.3 - - -tomcat - - org.springframework.boot.loader.WarLauncher - false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - - 0.0.4 - 2.6 - - 0.3.0 - 1.1.0 - - - diff --git a/cas/cas-server/settings.gradle b/cas/cas-server/settings.gradle new file mode 100644 index 0000000000..3ad50900ea --- /dev/null +++ b/cas/cas-server/settings.gradle @@ -0,0 +1 @@ +rootProject.name='cas' \ No newline at end of file diff --git a/cas/cas-server/src/main/jib/docker/entrypoint.sh b/cas/cas-server/src/main/jib/docker/entrypoint.sh new file mode 100755 index 0000000000..a3a0895b04 --- /dev/null +++ b/cas/cas-server/src/main/jib/docker/entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +#echo -e "\nChecking java..." +#java -version + +#echo -e "\nCreating CAS configuration directories..." +mkdir -p /etc/cas/config +mkdir -p /etc/cas/services + +#echo "Listing provided CAS docker artifacts..." +#ls -R docker/cas + +#echo -e "\nMoving CAS configuration artifacts..." +mv docker/cas/thekeystore /etc/cas 2>/dev/null +mv docker/cas/config/*.* /etc/cas/config 2>/dev/null +mv docker/cas/services/*.* /etc/cas/services 2>/dev/null + +#echo -e "\nListing CAS configuration under /etc/cas..." +#ls -R /etc/cas + +echo -e "\nRunning CAS..." +exec java -Xms512m -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -jar docker/cas/war/cas.war diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 7735fcabdc..185532f943 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -1,134 +1,4 @@ -## -# CAS Server Context Configuration -# -server.context-path=/cas -server.port=6443 - +server.port=8443 +spring.main.allow-bean-definition-overriding=true server.ssl.key-store=classpath:/etc/cas/thekeystore -server.ssl.key-store-password=changeit -server.ssl.key-password=changeit -# server.ssl.ciphers= -# server.ssl.client-auth= -# server.ssl.enabled= -# server.ssl.key-alias= -# server.ssl.key-store-provider= -# server.ssl.key-store-type= -# server.ssl.protocol= -# server.ssl.trust-store= -# server.ssl.trust-store-password= -# server.ssl.trust-store-provider= -# server.ssl.trust-store-type= - -server.max-http-header-size=2097152 -server.use-forward-headers=true -server.connection-timeout=20000 -server.error.include-stacktrace=NEVER - -server.tomcat.max-http-post-size=2097152 -server.tomcat.basedir=build/tomcat -server.tomcat.accesslog.enabled=true -server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) -server.tomcat.accesslog.suffix=.log -server.tomcat.max-threads=10 -server.tomcat.port-header=X-Forwarded-Port -server.tomcat.protocol-header=X-Forwarded-Proto -server.tomcat.protocol-header-https-value=https -server.tomcat.remote-ip-header=X-FORWARDED-FOR -server.tomcat.uri-encoding=UTF-8 - -spring.http.encoding.charset=UTF-8 -spring.http.encoding.enabled=true -spring.http.encoding.force=true - -## -#CAS CONFIG LOCATION -# -standalone.config=classpath:/etc/cas/config - - -## -# CAS Cloud Bus Configuration -# -spring.cloud.bus.enabled=false -# spring.cloud.bus.refresh.enabled=true -# spring.cloud.bus.env.enabled=true -# spring.cloud.bus.destination=CasCloudBus -# spring.cloud.bus.ack.enabled=true - -endpoints.enabled=false -endpoints.sensitive=true - -endpoints.restart.enabled=false -endpoints.shutdown.enabled=false - -management.security.enabled=true -management.security.roles=ACTUATOR,ADMIN -management.security.sessions=if_required -management.context-path=/status -management.add-application-context-header=false - -security.basic.authorize-mode=role -security.basic.enabled=false -security.basic.path=/cas/status/** - -## -# CAS Web Application Session Configuration -# -server.session.timeout=300 -server.session.cookie.http-only=true -server.session.tracking-modes=COOKIE - -## -# CAS Thymeleaf View Configuration -# -spring.thymeleaf.encoding=UTF-8 -spring.thymeleaf.cache=true -spring.thymeleaf.mode=HTML -## -# CAS Log4j Configuration -# -# logging.config=file:/etc/cas/log4j2.xml - -server.context-parameters.isLog4jAutoInitializationDisabled=true - -## -# CAS AspectJ Configuration -# -spring.aop.auto=true -spring.aop.proxy-target-class=true - -## -# CAS Authentication Credentials -# -#cas.authn.accept.users=casuser::Mellon -cas.authn.accept.users= -cas.authn.accept.name= - -#CAS Database Authentication Property -cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? -cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC -cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect -cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=1234 -cas.authn.jdbc.query[0].ddlAuto=none -#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver -cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver -cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=NONE - - -## -# CAS Delegated Authentication -# -cas.authn.pac4j.bitbucket.clientName=Bitbucket -cas.authn.pac4j.dropbox.clientName=Dropbox -cas.authn.pac4j.facebook.clientName=Facebook -cas.authn.pac4j.foursquare.clientName=Foursquare -cas.authn.pac4j.github.clientName=Github -cas.authn.pac4j.google.clientName=Google -cas.authn.pac4j.linkedIn.clientName=LinkedIn -cas.authn.pac4j.paypal.clientName=PayPal -cas.authn.pac4j.twitter.clientName=Twitter -cas.authn.pac4j.yahoo.clientName=Yahoo -cas.authn.pac4j.windowsLive.clientName=Windows Live -cas.authn.pac4j.wordpress.clientName=WordPress +server.ssl.key-store-password=changeit \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties deleted file mode 100644 index e39d68f312..0000000000 --- a/cas/cas-server/src/main/resources/cas.properties +++ /dev/null @@ -1,9 +0,0 @@ -cas.server.name: https://localhost:6443 -cas.server.prefix: https://localhost:643/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 - -logging.config: file:/etc/cas/config/log4j2.xml - -cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql index 79a4a48a82..104b515813 100644 --- a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -4,13 +4,13 @@ USE `test`; -- Dumping structure for table test.users CREATE TABLE IF NOT EXISTS `users` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `email` varchar(50) DEFAULT NULL, - `password` text DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`id`, `email`, `password`) VALUES - (1, 'test@test.com', 'Mellon'); + (1, 'test@test.com', 'Mellon'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties index 47a1477308..dda939bc1d 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -1,7 +1,15 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas +cas.serviceRegistry.initFromJson=true +cas.serviceRegistry.json.location=classpath:/etc/cas/services -cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services +cas.authn.accept.users= + +cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? +cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect +cas.authn.jdbc.query[0].user=root +cas.authn.jdbc.query[0].password=smattroot +cas.authn.jdbc.query[0].ddlAuto=none +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver +cas.authn.jdbc.query[0].fieldPassword=password +cas.authn.jdbc.query[0].passwordEncoder.type=NONE \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json new file mode 100644 index 0000000000..5d468945ff --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json @@ -0,0 +1,8 @@ +{ + "@class" : "org.apereo.cas.services.RegexRegisteredService", + "serviceId" : "http://cas-client:8900/login/cas", + "name" : "casSecuredApp", + "id" : 8900, + "logoutType" : "BACK_CHANNEL", + "logoutUrl" : "http://cas-client:8900/exit/cas" +} \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 77bf895249..a361bf03f9 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt deleted file mode 100644 index 12ef688a08..0000000000 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and /dev/null differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json deleted file mode 100644 index 336007e484..0000000000 --- a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "@class" : "org.apereo.cas.services.RegexRegisteredService", - "serviceId" : "^http://localhost:9000/login/cas", - "name" : "CAS Spring Secured App", - "description": "This is a Spring App that usses the CAS Server for it's authentication", - "id" : 19991, - "evaluationOrder" : 1 -} \ No newline at end of file diff --git a/cas/pom.xml b/cas/pom.xml index 77fae3b50a..e69de29bb2 100644 --- a/cas/pom.xml +++ b/cas/pom.xml @@ -1,23 +0,0 @@ - - - 4.0.0 - cas - cas - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - cas-secured-app - cas-server - - - diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index 2dbf159750..0a9bf76ac4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -8,5 +8,4 @@ This module contains articles about Java 9 core features - [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue) - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list) diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2b34ef3449..b97cd3216f 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -11,3 +11,4 @@ This module contains articles about the Java Set collection - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) - [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) +- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 8ba1b2400d..c89ba0c091 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -34,7 +34,23 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + 11 + 11 4.3 2.8.5 diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java similarity index 97% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java rename to core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java index 7dbcd2a3a3..2af040b13e 100644 --- a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java @@ -1,4 +1,4 @@ -package com.baeldung.java9.set; +package com.baeldung.set; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java similarity index 97% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java rename to core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java index 28e71affcc..d89927dfd6 100644 --- a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java +++ b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java @@ -1,9 +1,10 @@ -package com.baeldung.java9; +package com.baeldung.set; + +import org.junit.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/core-java-modules/core-java-concurrency-testing/.gitignore b/core-java-modules/core-java-concurrency-testing/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/README.md b/core-java-modules/core-java-concurrency-testing/README.md new file mode 100644 index 0000000000..fef74a6750 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Concurrency Testing Examples + +### Relevant Articles: +- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) + diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml new file mode 100644 index 0000000000..bb3e6f5152 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + core-java-concurrency-testing + 0.1.0-SNAPSHOT + core-java-concurrency-testing + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + + + diff --git a/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java new file mode 100644 index 0000000000..a678b047a8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent; + +public class MyCounter { + + private int count; + + public void increment() { + int temp = count; + count = temp + 1; + } + + public synchronized void incrementWithWait() throws InterruptedException { + int temp = count; + wait(100); + count = temp + 1; + } + + public int getCount() { + return count; + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java new file mode 100644 index 0000000000..6c76505347 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent; + +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE; +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE_INTERESTING; + +import org.openjdk.jcstress.annotations.Actor; +import org.openjdk.jcstress.annotations.Arbiter; +import org.openjdk.jcstress.annotations.JCStressTest; +import org.openjdk.jcstress.annotations.Outcome; +import org.openjdk.jcstress.annotations.State; +import org.openjdk.jcstress.infra.results.I_Result; + +@JCStressTest +@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.") +@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.") +@State +public class MyCounterJCStressUnitTest { + + private MyCounter counter; + + @Actor + public void actor1() { + counter.increment(); + } + + @Actor + public void actor2() { + counter.increment(); + } + + @Arbiter + public void arbiter(I_Result r) { + r.r1 = counter.getCount(); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java new file mode 100644 index 0000000000..eb4e77cae9 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import org.junit.Test; + +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; + +public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase { + + private MyCounter counter; + + @Override + public void initialize() { + counter = new MyCounter(); + } + + public void thread1() throws InterruptedException { + counter.increment(); + } + + public void thread2() throws InterruptedException { + counter.increment(); + } + + @SuppressWarnings("deprecation") + @Override + public void finish() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() throws Throwable { + TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000); + } +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java new file mode 100644 index 0000000000..4f3409b923 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Test; + +public class MyCounterSimpleUnitTest { + + @Test + public void testCounter() { + MyCounter counter = new MyCounter(); + for (int i = 0; i < 500; i++) + counter.increment(); + assertEquals(500, counter.getCount()); + } + + // @Test + public void testCounterWithConcurrency() throws InterruptedException { + int numberOfThreads = 100; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.execute(() -> { + counter.increment(); + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + + // @Test + public void testSummationWithConcurrencyAndWait() throws InterruptedException { + int numberOfThreads = 2; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.submit(() -> { + try { + counter.incrementWithWait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java new file mode 100644 index 0000000000..360c61b4f4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Rule; +import org.junit.Test; + +import com.google.code.tempusfugit.concurrency.ConcurrentRule; +import com.google.code.tempusfugit.concurrency.RepeatingRule; +import com.google.code.tempusfugit.concurrency.annotations.Concurrent; +import com.google.code.tempusfugit.concurrency.annotations.Repeating; + +public class MyCounterTempusFugitUnitTest { + + @Rule + public ConcurrentRule concurrently = new ConcurrentRule(); + @Rule + public RepeatingRule rule = new RepeatingRule(); + + private static MyCounter counter = new MyCounter(); + + @Test + @Concurrent(count = 2) + @Repeating(repetition = 10) + public void runsMultipleTimes() { + counter.increment(); + } + + @AfterClass + public static void annotatedTestRunsMultipleTimes() throws InterruptedException { + assertEquals(counter.getCount(), 20); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java new file mode 100644 index 0000000000..29b08996cd --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.google.testing.threadtester.AnnotatedTestRunner; +import com.google.testing.threadtester.ThreadedAfter; +import com.google.testing.threadtester.ThreadedBefore; +import com.google.testing.threadtester.ThreadedMain; +import com.google.testing.threadtester.ThreadedSecondary; + +public class MyCounterThreadWeaverUnitTest { + + private MyCounter counter; + + @ThreadedBefore + public void before() { + counter = new MyCounter(); + } + + @ThreadedMain + public void mainThread() { + counter.increment(); + } + + @ThreadedSecondary + public void secondThread() { + counter.increment(); + } + + @ThreadedAfter + public void after() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() { + new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 21044f82c4..e2a60ac384 100644 --- a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -3,7 +3,12 @@ package com.baeldung.jmx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.management.*; +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanRegistrationException; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; import java.lang.management.ManagementFactory; public class JMXTutorialMainlauncher { @@ -11,24 +16,21 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); public static void main(String[] args) { - // TODO Auto-generated method stub LOG.debug("This is basic JMX tutorial"); - ObjectName objectName = null; + try { - objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); - } catch (MalformedObjectNameException e) { - e.printStackTrace(); - } - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - Game gameObj = new Game(); - try { - server.registerMBean(gameObj, objectName); - } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + ObjectName objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new Game(), objectName); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | + MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); } + LOG.debug("Registration for Game mbean with the platform server is successfull"); LOG.debug("Please open jconsole to access Game mbean"); + while (true) { // to ensure application does not terminate } diff --git a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index f701ab2e45..dd8b3a420d 100644 --- a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -38,6 +38,11 @@ public class AddingNewLineToString { System.out.println("6. Using System.getProperty(\"line.separator\")"); rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); + + //7. Using %n + System.out.println("7. Using %n"); + rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall."; + System.out.println(rhyme); System.out.println("***HTML to rendered in a browser***"); //1. Line break for HTML using
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 5e7ffa37b9..ebdb11925b 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -42,7 +42,7 @@ core-java-collections-list core-java-collections-list-2 core-java-collections-list-3 - core-java-collections-set + core-java-concurrency-2 core-java-concurrency-advanced diff --git a/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java new file mode 100644 index 0000000000..7d33b38a0e --- /dev/null +++ b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.guava; + +import com.google.common.base.Throwables; +import org.junit.Test; + +import java.util.function.Supplier; + +public class ThrowablesUnitTest { + + @Test(expected = RuntimeException.class) + public void whenThrowable_shouldWrapItInRuntimeException() throws Exception { + try { + throwThrowable(Throwable::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Error.class) + public void whenError_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Error::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Exception.class) + public void whenException_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Exception::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + private void throwThrowable(Supplier exceptionSupplier) throws Throwable { + throw exceptionSupplier.get(); + } + +} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java index 2015909870..ba29d5c454 100644 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java +++ b/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.map; import org.junit.jupiter.api.Test; import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import static org.junit.jupiter.api.Assertions.*; @@ -121,4 +123,52 @@ class ProductUnitTest { assertNull(productsByName.get("E-Bike")); } + @Test + public void givenMutableKeyWhenKeyChangeThenValueNotFound() { + // Given + MutableKey key = new MutableKey("initial"); + + Map items = new HashMap<>(); + items.put(key, "success"); + + // When + key.setName("changed"); + + // Then + assertNull(items.get(key)); + } + + static class MutableKey { + private String name; + + public MutableKey(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MutableKey that = (MutableKey) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + } + } diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java similarity index 67% rename from jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java index ad34890996..bcfe615bc7 100644 --- a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java @@ -10,10 +10,18 @@ import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertNotNull; -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { +public class JGitBugManualTest { + + /** + * This test case expects one git repository to be present in local file system. + * Currently this test uses the Baeldung repository i.e. the current checkout repository. + * It finds the repository by tracking back and scan file system to find .git folder in + * the file system. + * + * Before running the test case ensure that the .git folder is present. + * + * @throws IOException + */ @Test public void testRevWalkDisposeClosesReader() throws IOException { try (Repository repo = Helper.openJGitRepository()) { diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties index b5fb841685..1055806ecf 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties index 04579e1dae..77aacf0d77 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql similarity index 100% rename from persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql rename to persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 31877255b2..7d95e0f342 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; +import org.junit.Ignore; import org.junit.Test; import com.baeldung.hibernate.criteria.model.Item; @@ -24,6 +25,7 @@ public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); @Test + @Ignore public void testPerformanceOfCriteria() { assertFalse(av.checkIfCriteriaTimeLower()); } diff --git a/pom.xml b/pom.xml index 04a2ce054c..9f132ca7a8 100644 --- a/pom.xml +++ b/pom.xml @@ -388,7 +388,6 @@ blade bootique - cas cdi checker-plugin @@ -730,6 +729,7 @@ spring-threads spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx @@ -899,7 +899,6 @@ blade bootique - cas cdi checker-plugin @@ -1231,6 +1230,7 @@ spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 2f8ef05bff..4b42528d0f 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,6 +42,11 @@ org.slf4j jcl-over-slf4j + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + org.jetbrains.kotlin @@ -175,8 +180,8 @@ 2.9.0 2.9.9 1.2.71 - com.baeldung.Spring5Application 4.5.8 + com.baeldung.Spring5Application diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java new file mode 100644 index 0000000000..ad660559c7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.html; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; + +@SpringBootApplication +public class HtmlApplication +{ + public static void main(String[] args) { + SpringApplication.run(HtmlApplication.class, args); + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java new file mode 100644 index 0000000000..23674d165e --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java @@ -0,0 +1,17 @@ +package com.baeldung.html; + +import org.springframework.http.*; +import org.springframework.stereotype.*; +import org.springframework.web.bind.annotation.*; + +@Controller +public class HtmlController +{ + @GetMapping(value = "/welcome", produces = MediaType.TEXT_HTML_VALUE) + @ResponseBody + public String welcomeAsHTML() + { + return "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + } +} diff --git a/spring-5-mvc/src/main/resources/application.properties b/spring-5-mvc/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5-mvc/src/main/resources/application.properties +++ b/spring-5-mvc/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ No newline at end of file diff --git a/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java new file mode 100644 index 0000000000..8eba4e8cf9 --- /dev/null +++ b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.html; + +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.test.web.servlet.*; +import org.springframework.test.web.servlet.request.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@WebMvcTest(HtmlController.class) +class HtmlControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + private final String expectedHtmlResponse = + "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + + @Test + void whenGETRequestToCorrectURL_thenReturnCorrectWelcomeMessage() throws Exception { + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/welcome")) + .andExpect(status().isOk()) + .andReturn(); + + String resultDOW = result.getResponse().getContentAsString(); + assertEquals(expectedHtmlResponse, resultDOW); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index e9d955edc0..2b1b1b7d12 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -52,7 +52,11 @@ shedlock-provider-jdbc-template ${shedlock.version}
- + + com.h2database + h2 + ${h2.version} + net.sourceforge.barbecue @@ -79,6 +83,7 @@ javase ${zxing.version} + @@ -185,6 +190,7 @@ 2.2.4 2.3.2 0.23.0 + 1.4.200 2.1.0 1.5-beta1 2.1 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..15422e1065 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java similarity index 85% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java index 060afe660e..cd5f63e962 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -5,9 +5,8 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component -class TaskScheduler { - - @Scheduled(cron = "*/15 * * * *") +class BaeldungTaskScheduler { + @Scheduled(cron = "0 0/15 * * * ?") @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java index 74ea39683d..440e1ffc6a 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -1,12 +1,16 @@ package com.baeldung.scheduling.shedlock; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; -import org.springframework.scheduling.annotation.EnableScheduling; + +import javax.sql.DataSource; @Configuration -@EnableScheduling -@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class SchedulerConfiguration { - + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider(dataSource); + } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml new file mode 100644 index 0000000000..3477520208 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + datasource: + driverClassName: org.h2.Driver + url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java new file mode 100644 index 0000000000..47f42c133f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.scheduling.shedlock; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BaeldungTaskSchedulerIntegrationTest { + @Autowired + private BaeldungTaskScheduler taskScheduler; + + @Test + public void whenShedLockConfigCorrect_thenSpringCtxtStartsWithoutError() { + // save the old out + PrintStream old = System.out; + + // Create a stream to hold the output for test + ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(consoleOutput); + System.setOut(ps); + //test + taskScheduler.scheduledTask(); + System.out.flush(); + String expected = "Running ShedLock task\n"; + assertThat(consoleOutput.toString()).isEqualTo(expected); + + //restore the old out + System.setOut(old); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties index 709574239b..7070d4c2f0 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties @@ -1 +1,4 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true +spring.mvc.static-path-pattern=/content/** +spring.webflux.static-path-pattern=/content/** +spring.resources.static-locations=classpath:/files/,classpath:/static-files \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html new file mode 100644 index 0000000000..15df316612 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html @@ -0,0 +1,10 @@ + + + + + Hello World! + + +Hello World! + + \ No newline at end of file diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java new file mode 100644 index 0000000000..65e249b15b --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + private static boolean isBeanFactoryPostProcessorRegistered = false; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){ + setBeanFactoryPostProcessorRegistered(true); + } + + public static boolean isBeanFactoryPostProcessorRegistered() { + return isBeanFactoryPostProcessorRegistered; + } + + public static void setBeanFactoryPostProcessorRegistered(boolean isBeanFactoryPostProcessorRegistered) { + CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered = isBeanFactoryPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java new file mode 100644 index 0000000000..6f99a5f0db --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanPostProcessor; + +public class CustomBeanPostProcessor implements BeanPostProcessor { + private static boolean isBeanPostProcessorRegistered = false; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName){ + setBeanPostProcessorRegistered(true); + return bean; + } + + public static boolean isBeanPostProcessorRegistered() { + return isBeanPostProcessorRegistered; + } + + public static void setBeanPostProcessorRegistered(boolean isBeanPostProcessorRegistered) { + CustomBeanPostProcessor.isBeanPostProcessorRegistered = isBeanPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java new file mode 100644 index 0000000000..404f323b66 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -0,0 +1,17 @@ +package com.baeldung.ioccontainer.bean; + +public class Student { + private static boolean isBeanInstantiated = false; + + public void postConstruct() { + setBeanInstantiated(true); + } + + public static boolean isBeanInstantiated() { + return isBeanInstantiated; + } + + public static void setBeanInstantiated(boolean isBeanInstantiated) { + Student.isBeanInstantiated = isBeanInstantiated; + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java new file mode 100644 index 0000000000..e9b491813e --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.ioccontainer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor; +import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor; +import com.baeldung.ioccontainer.bean.Student; + +public class IOCContainerAppUnitTest { + + @BeforeEach + @AfterEach + public void resetInstantiationFlag() { + Student.setBeanInstantiated(false); + CustomBeanPostProcessor.setBeanPostProcessorRegistered(false); + CustomBeanFactoryPostProcessor.setBeanFactoryPostProcessorRegistered(false); + } + + @Test + public void whenBFInitialized_thenStudentNotInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + + assertFalse(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenStudentInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Student student = (Student) factory.getBean("student"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenAppContInitialized_thenStudentInitialized() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenBFPProcessorAndBPProcessorNotRegAutomatically() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + assertFalse(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertFalse(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); + beanFactoryPostProcessor.postProcessBeanFactory(factory); + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + + CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); + factory.addBeanPostProcessor(beanPostProcessor); + Student student = (Student) factory.getBean("student"); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } +} diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml new file mode 100644 index 0000000000..e53dc11f89 --- /dev/null +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md new file mode 100644 index 0000000000..e1ddd727d7 --- /dev/null +++ b/spring-thymeleaf-3/README.md @@ -0,0 +1,5 @@ +## Spring Thymeleaf 3 + +This module contains articles about Spring with Thymeleaf + +## Relevant Articles: \ No newline at end of file diff --git a/spring-thymeleaf-3/pom.xml b/spring-thymeleaf-3/pom.xml new file mode 100644 index 0000000000..7677e50d79 --- /dev/null +++ b/spring-thymeleaf-3/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + spring-thymeleaf-3 + spring-thymeleaf-3 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.thymeleaf.cssandjs.CssAndJsApplication + JAR + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + spring-thymeleaf-3 + + + + 1.8 + 1.8 + 2.2 + + + diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java similarity index 50% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java rename to spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java index cb0d0c1532..2ccca82497 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java @@ -1,14 +1,11 @@ -package com.baeldung.boot; +package com.baeldung.thymeleaf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; @SpringBootApplication public class Application { - private static ApplicationContext applicationContext; - public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); + SpringApplication.run(Application.class, args); } } diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java new file mode 100644 index 0000000000..fc6c142b8b --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CssAndJsApplication { + public static void main(String[] args) { + SpringApplication.run(CssAndJsApplication.class, args); + } +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java new file mode 100644 index 0000000000..b56a7b468e --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java @@ -0,0 +1,15 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CssAndJsController { + + @GetMapping("/styled-page") + public String getStyledPage(Model model) { + model.addAttribute("name", "Baeldung Reader"); + return "cssandjs/styledPage"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js new file mode 100644 index 0000000000..e192e6358e --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js @@ -0,0 +1,7 @@ +function showAlert() { + alert("The button was clicked!"); +} + +function showName(name) { + alert("Here's the name: " + name); +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css new file mode 100644 index 0000000000..1f57b4616a --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css @@ -0,0 +1,18 @@ +h2 { + font-family: sans-serif; + font-size: 1.5em; + text-transform: uppercase; +} + +strong { + font-weight: 700; + background-color: yellow; +} + +p { + font-family: sans-serif; +} + +label { + font-weight: 600; +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html new file mode 100644 index 0000000000..12e4fc9227 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html @@ -0,0 +1,20 @@ + + + + + Add CSS and JS to Thymeleaf + + + + + +

Carefully Styled Heading

+

+ This is text on which we want to apply very special styling. +

+

+ + + \ No newline at end of file diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..b7cfa140f0 --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + + } +} diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java new file mode 100644 index 0000000000..365608bd2a --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.thymeleaf.cssandjs; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = CssAndJsApplication.class) +public class CssAndJsControllerIntegrationTest { + @Autowired + private WebApplicationContext context; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); + } + + @Test + public void whenCalledGetStyledPage_thenReturnContent() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/styled-page")) + .andExpect(status().isOk()) + .andExpect(view().name("cssandjs/styledPage")) + .andExpect(content().string(containsString("Carefully Styled Heading"))); + } +}