import org.apache.tools.ant.taskdefs.condition.* import org.gradle.internal.logging.text.* import org.apereo.cas.metadata.* import java.nio.file.* import static org.gradle.internal.logging.text.StyledTextOutput.Style buildscript { repositories { if (project.privateRepoUrl) { maven { url project.privateRepoUrl credentials { username = project.privateRepoUsername password = System.env.PRIVATE_REPO_TOKEN } } } mavenLocal() mavenCentral() gradlePluginPortal() maven { url 'https://oss.sonatype.org/content/repositories/snapshots' mavenContent { snapshotsOnly() } } maven { url "https://repo.spring.io/milestone" mavenContent { releasesOnly() } } } dependencies { classpath "org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}" classpath "io.freefair.gradle:maven-plugin:${project.gradleFreeFairPluginVersion}" classpath "io.freefair.gradle:lombok-plugin:${project.gradleFreeFairPluginVersion}" classpath "io.spring.gradle:dependency-management-plugin:${project.gradleDependencyManagementPluginVersion}" classpath "gradle.plugin.com.google.cloud.tools:jib-gradle-plugin:${project.jibVersion}" classpath "de.undercouch:gradle-download-task:${project.gradleDownloadTaskVersion}" classpath "org.apache.ivy:ivy:${project.ivyVersion}" classpath "org.apereo.cas:cas-server-core-api-configuration-model:${project.'cas.version'}" classpath "org.apereo.cas:cas-server-core-configuration-metadata-repository:${project.'cas.version'}" } } repositories { if (project.privateRepoUrl) { maven { url project.privateRepoUrl credentials { username = project.privateRepoUsername password = System.env.PRIVATE_REPO_TOKEN } } } mavenLocal() mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/releases' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots' mavenContent { snapshotsOnly() } } maven { url 'https://build.shibboleth.net/nexus/content/repositories/releases/' } maven { url "https://repo.spring.io/milestone" mavenContent { releasesOnly() } } } apply plugin: "io.freefair.war-overlay" apply plugin: "war" apply plugin: "org.springframework.boot" apply plugin: "io.freefair.lombok" apply from: rootProject.file("gradle/springboot.gradle") apply from: rootProject.file("gradle/jib.gradle") configurations.all { resolutionStrategy { cacheChangingModulesFor 0, "seconds" cacheDynamicVersionsFor 0, "seconds" preferProjectModules() def failIfConflict = project.hasProperty("failOnVersionConflict") && Boolean.valueOf(project.getProperty("failOnVersionConflict")) if (failIfConflict) { failOnVersionConflict() } } } war { entryCompression = ZipEntryCompression.STORED enabled = false } task run(group: "build", description: "Run the CAS web application in embedded container mode") { dependsOn 'build' doLast { def casRunArgs = Arrays.asList("-server -noverify -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1".split(" ")) javaexec { main = "-jar" jvmArgs = casRunArgs args = ["build/libs/cas.war"] systemProperties = System.properties logger.info "Started ${commandLine}" } } } task setExecutable(group: "CAS", 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: "CAS", 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: "CAS", 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/cas.war"] systemProperties = System.properties logger.info "Started ${commandLine}" } } } task showConfiguration(group: "CAS", 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: "CAS", 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 ${project.version}" 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 project.version } } } task springBootVersion(description: "Display current Spring Boot version") { doLast { println rootProject.springBootVersion } } task containerImageCoords(group: "CAS", description: "Display the coordinates for the container image") { doFirst { println "${project.'containerImageOrg'}/${project.'containerImageName'}:${project.version}" } } task createKeystore(group: "CAS", description: "Create CAS keystore") { doFirst { def certDir = project.getProperty("certDir") def serverKeyStore = project.getProperty("serverKeystore") def exportedServerCert = project.getProperty("exportedServerCert") def storeType = project.getProperty("storeType") def keystorePath = "$certDir/$serverKeyStore" def serverCert = "$certDir/$exportedServerCert" mkdir certDir 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}", "-storetype", storeType } logger.info "Exporting cert from keystore..." exec { workingDir "." commandLine "keytool", "-exportcert", "-alias", "cas", "-storepass", "changeit", "-keystore", keystorePath, "-file", serverCert } logger.info "Import $serverCert into your Java truststore (\$JAVA_HOME/lib/security/cacerts)" } } task unzipWAR(type: Copy, group: "CAS", description: "Explodes the CAS web application archive") { dependsOn 'build' from zipTree("build/libs/cas.war") into "${buildDir}/app" doLast { println "Unzipped WAR into ${buildDir}/app" } } task verifyRequiredJavaVersion { def currentVersion = org.gradle.api.JavaVersion.current() logger.info "Checking current Java version ${currentVersion} for required Java version ${project.targetCompatibility}" if (!currentVersion.name.equalsIgnoreCase("${project.targetCompatibility}")) { throw new GradleException("Current Java version ${currentVersion} does not match required Java version ${project.targetCompatibility}") } } task copyCasConfiguration(type: Copy, group: "CAS", 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() } } apply plugin: "de.undercouch.download" def tomcatDirectory = "${buildDir}/apache-tomcat-${tomcatVersion}" project.ext."tomcatDirectory" = tomcatDirectory def explodedDir = "${buildDir}/app" def explodedResourcesDir = "${buildDir}/cas-resources" def resourcesJarName = "cas-server-webapp-resources" def templateViewsJarName = "cas-server-support-thymeleaf" task unzip(type: Copy, group: "CAS", description: "Explodes the CAS archive and resources jar from the CAS web application archive") { dependsOn unzipWAR from zipTree("${explodedDir}/WEB-INF/lib/${templateViewsJarName}-${project.'cas.version'}.jar") into explodedResourcesDir from zipTree("${explodedDir}/WEB-INF/lib/${resourcesJarName}-${project.'cas.version'}.jar") into explodedResourcesDir duplicatesStrategy = DuplicatesStrategy.EXCLUDE doLast { println "Exploded WAR resources into ${explodedResourcesDir}" } } task downloadShell(group: "Shell", description: "Download CAS shell jar from snapshot or release maven repo") { doFirst { mkdir "${project.shellDir}" } doLast { def downloadFile if (isRunningCasServerSnapshot()) { def snapshotDir = "https://oss.sonatype.org/content/repositories/snapshots/org/apereo/cas/cas-server-support-shell/${project.'cas.version'}/" def files = new org.apache.ivy.util.url.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/${project.'cas.version'}/cas-server-support-shell-${project.'cas.version'}.jar" } logger.info "Downloading file: ${downloadFile}" download { src downloadFile dest new File("${project.shellDir}", "cas-server-support-shell-${project.'cas.version'}.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-${project.'cas.version'}.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-${project.'cas.version'}.jar """ } } task listTemplateViews(group: "CAS", description: "List all CAS views") { dependsOn unzip doFirst { fileTree(explodedResourcesDir).matching { include "**/*.html" } .collect { return it.path.replace(explodedResourcesDir, "") } .toSorted() .each { println it } } } task exportConfigMetadata(group: "CAS", description: "Export collection of CAS properties") { doLast { def file = new File(project.rootDir, 'config-metadata.properties') def queryType = ConfigurationMetadataCatalogQuery.QueryTypes.CAS if (project.hasProperty("queryType")) { queryType = ConfigurationMetadataCatalogQuery.QueryTypes.valueOf(project.findProperty("queryType")) } file.withWriter('utf-8') { writer -> def props = CasConfigurationMetadataCatalog.query( ConfigurationMetadataCatalogQuery.builder() .queryType(queryType) .build()) .properties() props.each { property -> writer.writeLine("# Type: ${property.type}"); writer.writeLine("# Module: ${property.module}") writer.writeLine("# Owner: ${property.owner}") if (property.deprecationLevel != null) { writer.writeLine("# This setting is deprecated with a severity level of ${property.deprecationLevel}.") if (property.deprecationReason != null) { writer.writeLine("# because ${property.deprecationReason}") } if (property.deprecationReason != null) { writer.writeLine("# Replace with: ${property.deprecationReason}") } } writer.writeLine("#") def description = property.description.replace("\n", "\n# ").replace("\r", "") description = org.apache.commons.text.WordUtils.wrap(description, 70, "\n# ", true) writer.writeLine("# ${description}") writer.writeLine("#") writer.writeLine("# ${property.name}: ${property.defaultValue}") writer.writeLine("") } } println "Configuration metadata is available at ${file.absolutePath}" } } task getResource(group: "CAS", description: "Fetch a CAS resource and move it into the overlay") { dependsOn unzip doFirst { def resourceName = project.getProperty("resourceName") def results = fileTree(explodedResourcesDir).matching { include "**/${resourceName}.*" include "**/${resourceName}" } if (results.isEmpty()) { println "No resources could be found matching ${resourceName}" return } if (results.size() > 1) { println "Multiple resources found matching ${resourceName}:\n" results.each { println "\t-" + it.path.replace(explodedResourcesDir, "") } println "\nNarrow down your search criteria and try again." 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() { return "${project.'cas.version'}".contains("-SNAPSHOT") } task createTheme(group: "CAS", description: "Create theme directory structure in the overlay") { doFirst { def theme = project.getProperty("theme") def builder = new FileTreeBuilder() new File("src/main/resources/${theme}.properties").delete() builder.src { main { resources { "static" { themes { "${theme}" { css { 'cas.css'('') } js { 'cas.js'('') } images { '.ignore'('') } } } } templates { "${theme}" { fragments { } } } "${theme}.properties"("""cas.standard.css.file=/themes/${theme}/css/cas.css cas.standard.js.file=/themes/${theme}/js/cas.js """) } } } } } springBoot { buildInfo() mainClass = "org.apereo.cas.web.CasWebApplication" } sourceSets { bootRunSources { resources { srcDirs new File("//etc/cas/templates/"), new File("${project.getProjectDir()}/src/main/resources/") } } } java { toolchain { languageVersion = JavaLanguageVersion.of(project.targetCompatibility) } } bootBuildImage { imageName = "${project.'containerImageOrg'}/${project.'containerImageName'}:${project.version}" } dependencies { /** * Do NOT modify the lines below or else you will risk breaking dependency management. */ implementation enforcedPlatform("org.apereo.cas:cas-server-support-bom:${project.'cas.version'}") implementation platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES) /** * CAS dependencies and modules may be listed here. * * There is no need to specify the version number for each dependency * since versions are all resolved and controlled by the dependency management * plugin via the CAS bom. **/ implementation "org.apereo.cas:cas-server-core-api-configuration-model" implementation "org.apereo.cas:cas-server-webapp-init" if (project.hasProperty("casModules")) { def dependencies = project.getProperty("casModules").split(",") dependencies.each { def projectsToAdd = rootProject.subprojects.findAll {project -> project.name == "cas-server-core-${it}" || project.name == "cas-server-support-${it}" } projectsToAdd.each {implementation it} } } developmentOnly "org.springframework.boot:spring-boot-devtools:${project.springBootVersion}" } bootWar { 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 "cas.war" baseName "cas" entryCompression = ZipEntryCompression.STORED /* attachClasses = true classesClassifier = 'classes' archiveClasses = true */ 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}:${project.'cas.version'}@war" provided = false excludes = ["WEB-INF/lib/servlet-api-2*.jar"] /* excludes = ["WEB-INF/lib/somejar-1.0*"] enableCompilation = true includes = ["*.xyz"] targetPath = "sub-path/bar" skip = false */ } } }