Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

15.4 KB
Raw Blame
// Common configuration applied to all projects

import java.io.Serializable
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFileAttributes
import java.nio.file.attribute.PosixFilePermission
import java.util.stream.Collectors
import java.util.stream.StreamSupport

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility

import org.gradle.language.base.plugins.LifecycleBasePlugin
import groovy.json.JsonSlurper
import org.jetbrains.gradle.ext.Application
import org.jetbrains.gradle.ext.JUnit

import cz.habarta.typescript.generator.DateMapping
import cz.habarta.typescript.generator.EnumMapping
import cz.habarta.typescript.generator.Jackson2Configuration
import cz.habarta.typescript.generator.JsonLibrary
import cz.habarta.typescript.generator.ModuleDependency
import cz.habarta.typescript.generator.NullabilityDefinition
import cz.habarta.typescript.generator.OptionalProperties
import cz.habarta.typescript.generator.RestNamespacing
import cz.habarta.typescript.generator.TypeScriptFileType
import cz.habarta.typescript.generator.TypeScriptOutputKind

import static org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS
import static org.apache.tools.ant.taskdefs.condition.Os.isFamily
import static org.jetbrains.gradle.ext.ShortenCommandLine.MANIFEST


// Configure versions in gradle.properties (putting a gradle.properties file
// in a subproject only overrides root properties of same name for the actual
// subproject, not for its children!)

configurations.all {
  resolutionStrategy {

    //failOnVersionConflict()

    // This has been replaced with eclipse angus implementation
    exclude group: "com.sun.activation", module: "jakarta.activation"

    // This has been replaced with org.bouncycastle bcpkix-jdk18on
    exclude group: "org.bouncycastle", module: "bcpkix-jdk15on"

    // This has been replaced with org.bouncycastle bcprov-jdk18on
    exclude group: "org.bouncycastle", module: "bcprov-jdk15on"

    eachDependency { DependencyResolveDetails details ->
      if (details.requested.group == 'org.eclipse.angus' && details.requested.name == 'angus-activation' && details.requested.version == '1.0.0') {
        details.useVersion '2.0.0'
      }
      if (details.requested.group == 'commons-io' && details.requested.name == 'commons-io') {
        details.useVersion '2.14.0'
      }
    }
  }
}

// Ensure git hook creation task is executed
if (project == rootProject) {

  project.afterEvaluate {
    tasks.configureEach { task ->
      if (task.name in ['encryptFiles', 'decryptFiles']) {
        task.notCompatibleWithConfigurationCache("GradleFileEncrypt stores javax.crypto.SecretKey/SecretKeySpec task state")
      }

      if (task.name in [
                'findSonatypeStagingRepository',
                'closeSonatypeStagingRepository',
                'releaseSonatypeStagingRepository',
                'closeAndReleaseSonatypeStagingRepository'
              ]) {
        // See: https://github.com/gradle-nexus/publish-plugin/issues/221
        task.notCompatibleWithConfigurationCache("Gradle Nexus Publish plugin task keeps Gradle Task/Project state")
      }
    }

    if (rootProject.hasProperty("gradleFileEncrypt")) {
      println("File encryption plugin config found, configuring git pre commit hook and decrypt task dependency")
      try {
        // Write git hook for encryption plugin checks before any commit
        def path = Paths.get(rootProject.projectDir.path, ".git/hooks/pre-commit")
        def f = path.toFile()
        f.text = """#!/bin/sh

echo "***** Running gradle encryption plugin checkFilesGitIgnored task ******"

./gradlew checkFilesGitIgnoredNew

status=\$?

if [ \$status != 0 ]; then
   echo "***** One or more encrypted files are not listed in a .gitignore - please add to prevent unencrypted version of file(s) from being committed *****"
fi

exit \$status
"""
        Set<PosixFilePermission> perms = Files.readAttributes(path, PosixFileAttributes.class).permissions()
        perms.add(PosixFilePermission.OWNER_WRITE)
        perms.add(PosixFilePermission.OWNER_READ)
        perms.add(PosixFilePermission.OWNER_EXECUTE)
        perms.add(PosixFilePermission.GROUP_WRITE)
        perms.add(PosixFilePermission.GROUP_READ)
        perms.add(PosixFilePermission.GROUP_EXECUTE)
        perms.add(PosixFilePermission.OTHERS_READ)
        perms.add(PosixFilePermission.OTHERS_EXECUTE)
        Files.setPosixFilePermissions(path, perms)
      } catch (Exception ignored) {}

      // Add dependency on decrypt task for deployment installDist only if GFE_PASSWORD defined
      def password = System.env.GFE_PASSWORD
      if (password != null) {
        project(':deployment').afterEvaluate { deploymentProject ->
          try {
            def decryptTaskProvider = rootProject.tasks.named("decryptFiles")
            deploymentProject.tasks.named('installDist').configure { installDist ->
              installDist.dependsOn(decryptTaskProvider)
              installDist.mustRunAfter(decryptTaskProvider)
            }
          } catch (Exception ex) {
            println("Failed to add decryptFiles task dependency: " + ex)
          }
        }
      }
    } else {
      // Remove git hook
      try {
        Files.delete(Paths.get(rootProject.projectDir.path, ".git/hooks/pre-commit"))
      } catch (Exception ignored) {
      }
    }
  }
}


// Configure Conditional plugins
if (project == rootProject) {
  pluginManager.apply('org.jetbrains.gradle.plugin.idea-ext')

  // Configure IDEA
  if (project.hasProperty("idea") && idea.project) {
    // IDEA settings
    idea.project.settings {
      compiler {
        javac {
          javacAdditionalOptions = "-parameters"
        }
      }
      runConfigurations {
        defaults(JUnit) {
          shortenCommandLine = MANIFEST
          workingDirectory = projectDir.toString()
        }
        defaults(Application) {
          mainClass = 'org.openremote.manager.Main'
          shortenCommandLine = MANIFEST
          workingDirectory = projectDir.toString()
        }
        "Demo Setup"(Application) {
          moduleName = getProject().idea.module.name + ".setup.demo"
          envs = [
            OR_SETUP_TYPE: "demo"
          ]
        }
        "Clustering Setup"(Application) {
          moduleName = getProject().idea.module.name + ".setup.clustering"
          envs = [
            OR_SETUP_TYPE: "clustering"
          ]
        }
        "Notification Setup"(Application) {
          moduleName = getProject().idea.module.name + ".setup.notification"
          envs = [
            OR_SETUP_TYPE: "notification",
            OR_APP_DOCROOT: "manager/build/install/manager/web"
          ]
        }
        "Date Time Setup"(Application) {
          moduleName = getProject().idea.module.name + ".setup.datetime"
          envs = [
            OR_SETUP_TYPE: "datetime",
            OR_APP_DOCROOT: "manager/build/install/manager/web"
          ]
        }
        "Test Setup"(Application) {
          moduleName = getProject().idea.module.name + ".setup.integration"
        }
        "Empty"(Application) {
          moduleName = getProject().idea.module.name + ".manager.main"
        }
      }
    }
  }
}

subprojects {
  // Give test tasks more memory (Gradle 5 reduced this to 512MB)
  tasks.withType(Test) {
    maxHeapSize = "2g"
  }

  // Give compiler tasks more memory
  tasks.withType(GroovyCompile) {
    groovyOptions.forkOptions.memoryMaximumSize = '2g' // Set max heap to 2 GB
  }
}

// Default repositories for dependency resolution
repositories {
  mavenLocal()
  // Needs to be above central due to org.geotools:gt-main issues
  maven {
    url = "https://repo.osgeo.org/repository/release/"
    content {
      includeGroup "it.geosolutions.jgridshift"
      includeGroup "org.eclipse.imagen"
      includeGroupByRegex "org\\.geotools.*"
    }
  }
  mavenCentral()
  maven {
    url = "https://pkgs.dev.azure.com/OpenRemote/OpenRemote/_packaging/OpenRemote/maven/v1"
  }
  maven {
    url = "https://central.sonatype.com/repository/maven-snapshots"
  }
  maven {
    url = "https://repo.jenkins-ci.org/releases/"
  }
  maven {
    url = 'https://jitpack.io'
  }
  maven {
    url = 'https://plugins.gradle.org/m2'
  }
}

// Eclipse needs help
pluginManager.apply('eclipse')
// Editors using Eclipse JDT language server
eclipse {
  classpath {
    baseSourceOutputDir.set(file('build/eclipse'))
    defaultOutputDir = file('build/eclipse/default')
  }
}

// Intellij needs help
pluginManager.apply('idea')
// Use the same output directories in IDE as in gradle
idea {
  module {
    outputDir = file('build/classes/main')
    testOutputDir = file('build/classes/test')
    excludeDirs += file(".node")
    excludeDirs += file("node_modules")
    excludeDirs += file("dist")
    excludeDirs += file("lib")
    excludeDirs += file("build")
  }
}

def getYarnInstallTask() {
  // Just use openremote repo yarn install
  tasks.getByPath(":yarnInstall")
}

/**
 * This defines reusable config for the typescript generator plugin
 */
def createTSGeneratorConfigForModel(String outputFileName, Project...customProjectsToScan) {
  def config = createTSGeneratorConfig(false, outputFileName, customProjectsToScan) << {
    extensionClasses = [
      "org.openremote.model.util.AssetModelInfoExtension",
      "CustomExtension",
      "JsonSerializeExtension"
    ]
    customTypeMappings = [
      "com.fasterxml.jackson.databind.node.ObjectNode:{ [id: string]: unknown }",
      "java.lang.Class<T>:string",
      "org.openremote.model.attribute.MetaItem<T>:any"
    ]
    customTypeProcessor = "CustomTypeProcessor"
    generateInfoJson = true
  }
  return config
}
def createTSGeneratorConfigForClient(String outputFileName, File modelInfoJson, Project...customProjectsToScan) {
  def config = createTSGeneratorConfig(true, outputFileName, customProjectsToScan) << {
    extensionClasses = [
      "CustomExtension",
      "JsonSerializeExtension",
      "AggregatedApiClient",
      "cz.habarta.typescript.generator.ext.AxiosClientExtension"
    ]
    customTypeMappings = [
      "com.fasterxml.jackson.databind.node.ObjectNode:{ [id: string]: unknown }",
      "java.lang.Class<T>:string",
      "org.openremote.model.attribute.MetaItem<T>:any",
      "org.openremote.model.asset.Asset<T>:Model.Asset",
      "org.openremote.model.asset.AssetDescriptor<T>:Model.AssetDescriptor",
      "org.openremote.model.asset.agent.Agent<T,U,V>:Model.Agent",
      "org.openremote.model.asset.agent.AgentDescriptor<T,U,V>:Model.AgentDescriptor",
      "org.openremote.model.value.MetaItemDescriptor<T>:Model.MetaItemDescriptor",
      "org.openremote.model.value.ValueDescriptor<T>:Model.ValueDescriptor"
    ]
    moduleDependencies = [
      ModuleDependency.module(
      "@openremote/model",
      "Model",
      modelInfoJson,
      (String) null,
      (String) null
      )
    ]
    restNamespacing = RestNamespacing.perResource
  }
  return config
}
def createTSGeneratorConfig(boolean outputAPIClient, String outputFileName, Project...customProjectsToScan) {

  def classPatternGlobs = Arrays.stream(customProjectsToScan).flatMap { project ->
    return project.sourceSets.findByName('main').java.srcDirs.stream().map {
      def srcPath = it
      def isPackageDir = true
      while (srcPath != null && isPackageDir) {
        def files = srcPath.listFiles()
        isPackageDir = files != null && files.length == 1 && files[0].isDirectory()
        if (isPackageDir) {
          srcPath = files[0]
        }
      }
      Path packagePath = it.toPath().relativize(srcPath.toPath())
      return StreamSupport
              .stream(packagePath.spliterator(), false)
              .map({ java.nio.file.Path path -> path.toString() })
              .collect(Collectors.joining(".")) + (outputAPIClient ? ".**Resource" : ".**")
    }
  }.toList()

  return {
    jsonLibrary = JsonLibrary.jackson2
    classPatterns = [(outputAPIClient ? "org.openremote.model.**Resource" : "org.openremote.model.**")] + classPatternGlobs
    customTypeNamingFunction = "function(name, simpleName) { if (name.indexOf(\"\$\") > 0) return name.substr(name.lastIndexOf(\".\")+1).replace(\"\$\",\"\"); }"
    nullabilityDefinition = NullabilityDefinition.nullAndUndefinedInlineUnion
    nullableAnnotations = ["org.checkerframework.checker.nullness.qual.Nullable"]
    excludeClassPatterns = [
      "org.openremote.model.event.shared.*Filter**",
      "org.openremote.model.util.**",
      "org.openremote.model.flow.**",
      "java.io.**",
      //"java.lang.**",
      "org.hibernate.**",
      "jakarta.**"
    ]
    mapEnum = EnumMapping.asEnum
    mapDate = DateMapping.asNumber
    optionalProperties = OptionalProperties.all // TODO: cleanup model to be more explicit about optional params
    outputFileType = TypeScriptFileType.implementationFile
    outputKind = TypeScriptOutputKind.module
    outputFile = outputFileName

    def jackson2Config = new Jackson2Configuration()
    jackson2Config.fieldVisibility = Visibility.ANY
    jackson2Config.creatorVisibility = Visibility.ANY
    jackson2Config.getterVisibility = Visibility.NONE
    jackson2Config.isGetterVisibility = Visibility.NONE
    jackson2Config.setterVisibility = Visibility.NONE
    jackson2Configuration.set(jackson2Config)

    jackson2Modules = [
      "com.fasterxml.jackson.datatype.jdk8.Jdk8Module",
      "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule",
      "com.fasterxml.jackson.module.paramnames.ParameterNamesModule"
    ]
  }
}

ext {
  getYarnInstallTask = this.&getYarnInstallTask
  createTSGeneratorConfigForClient = this.&createTSGeneratorConfigForClient
  createTSGeneratorConfigForModel = this.&createTSGeneratorConfigForModel
}

// Add UI tasks
ext.npmCommand = { cmd ->
  isFamily(FAMILY_WINDOWS) ? "${cmd}.cmd" : cmd
}

// Add yarn tasks
tasks.register('yarnInstall', Exec) {
  commandLine npmCommand("yarn"), "install"
}
tasks.register('yarnInstallForce', Exec) {
  commandLine npmCommand("yarn"), "install", "--force"
}
tasks.register('npmClean', Exec) {
  dependsOn getYarnInstallTask()
  commandLine npmCommand("yarn"), "run", "clean"
}
tasks.register('npmServe', Exec) {
  dependsOn getYarnInstallTask()
  commandLine npmCommand("yarn"), "run", "serve"
}
tasks.register('npmPrepare', Exec) {
  dependsOn getYarnInstallTask()
  commandLine npmCommand("yarn"), "pack"
}
tasks.register('npmPublish', Exec) {
  dependsOn getYarnInstallTask()
  commandLine npmCommand("yarn"), "npm", "publish", "--access", "public"
}
tasks.register('npmServeProduction', Exec) {
  dependsOn getYarnInstallTask()
  commandLine npmCommand("yarn"), "run", "serveProduction"
}

// Add typescript tasks
tasks.register('tscWatch', Exec) {
  commandLine npmCommand("npx"), "tsc", "-b", "--watch"
}

// Configure Java build
plugins.withType(JavaPlugin).whenPluginAdded {

  // Use Java 21
  tasks.withType(JavaCompile) {
    sourceCompatibility = JavaVersion.VERSION_21
    targetCompatibility = JavaVersion.VERSION_21
    def warnLogFile = file("$buildDir/${name}Warnings.log")
    logging.addStandardErrorListener(new StandardOutputListener() {
              void onOutput(CharSequence output) {
                warnLogFile << output
              }
            })
    options.compilerArgs += ["-Xlint:unchecked", "-Xlint:deprecation", "-parameters"]
    options.encoding = 'UTF-8'
  }

  // Allow dependencyInsight checks across all projects
  tasks.register('allDependencyInsight', DependencyInsightReportTask) {}

  base {
    // JAR/ZIP base name is the fully qualified subproject name
    archivesName = "${rootProject.name}${path.replaceAll(":", "-")}"
  }
}

// Configure Spotless
if (project == rootProject) {
  apply from: "${rootDir}/spotless.gradle"
}

// POM generator