Kotlin lowercase Function - kotlin

I am new to kotlin, so I am sorry in advance, if this is a simple misstake.
I am trying at the moment to rewrite an api (written in Kotlin) to java 17.
Everything worked so far. But now I am getting following deprecated message:
'toLowerCase(): String' is deprecated. Use lowercase() instead.
Of course I know what it means, so I tried doing it like in the following Picture:
https://i.stack.imgur.com/vT8k5.png
But why doesnt it find the lowercase Function?
This is in my build.gradle:
plugins {
id 'org.jetbrains.kotlin.jvm'
id "org.jetbrains.kotlin.kapt"
id "org.jetbrains.dokka"
id "java-library"
id "maven-publish"
id "jacoco"
id "io.gitlab.arturbosch.detekt"
id "org.jlleitschuh.gradle.ktlint"
id "com.github.gmazzo.buildconfig"
}
apply from: "${rootDir}/gradle/dependencies.gradle"
tasks.withType(org.jetbrains.dokka.gradle.DokkaTask).configureEach {
dokkaSourceSets {
configureEach {
sourceLink {
localDirectory.set(file("src/main/kotlin"))
remoteUrl.set(uri("").toURL())
}
externalDocumentationLink { url.set(new URL("https://square.github.io/retrofit/2.x/retrofit/")) }
externalDocumentationLink { url.set(new URL("https://square.github.io/okhttp/3.x/okhttp/")) }
externalDocumentationLink { url.set(new URL("https://square.github.io/moshi/1.x/moshi/")) }
}
}
}
tasks.dokkaJavadoc.configure {
outputDirectory.set(javadoc.destinationDir)
}
task sourceJar(type: Jar) {
archiveClassifier = "sources"
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: dokkaJavadoc) {
archiveClassifier = "javadoc"
from javadoc.destinationDir
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "17"
allWarningsAsErrors = true
freeCompilerArgs = ["-Xjsr305=strict", "-progressive"]
}
}
kapt {
useBuildCache = true
}
test {
finalizedBy jacocoTestReport
useJUnitPlatform()
}
buildConfig {
packageName("my.package") // forces the package. Defaults to '${project.group}'
useKotlinOutput() // adds `internal` modifier to all declarations
buildConfigField("String", "packageName", "\"my.package\"")
buildConfigField("String", "version", provider { "\"${project.version}\"" })
}
jacoco {
setToolVersion(jacocoVersion)
}
jacocoTestReport {
reports {
xml.required = true
html.required = false
}
}
ktlint {
disabledRules = ["import-ordering"]
version = ktlintVersion
reporters {
reporter "checkstyle"
}
}
detekt {
version = detektVersion
buildUponDefaultConfig = true
config = files("$rootDir/config/detekt.yml")
}
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
compileKotlin {
kotlinOptions {
jvmTarget = "17"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "17"
}
}

Ensure your kotlin-stdlib version is 1.5 or above. Check this out

Related

Can not ready file text within build.gradle.kts

I am trying to print a kotlin class before compiling it to generate another class. I tried many methods to be sure about printing the file text before compiling it through File.readText() but nothings success-ed always printing code joined with symbols as the following screenshot.
My Gradle code
tasks.findByName("compileKotlin")
?.dependsOn(tasks.register("compileKotlin2") {
doFirst {
var names2 = "filesPath= "
fileTree("$buildDir\\classes\\kotlin\\main\\tech\\example\\ecommerce\\ecommerce\\controller\\")
.visit {
if (this.file.name != "WebPagesController.class") {
names2 += this.file.path + "\n"
println(file(this.file.path).readText())
}
}
println(names2)
}
})
Full build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("plugin.jpa") version "1.3.61"
id("org.springframework.boot") version "2.2.5.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm") version "1.3.61"
kotlin("plugin.spring") version "1.3.61"
}
group = "tech.example.ecommerce"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
repositories {
mavenCentral()
}
dependencies {
// springframework
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("mysql:mysql-connector-java")
// kotlin
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
// testing
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
}
tasks.findByName("compileKotlin")
?.dependsOn(tasks.register("compileKotlin2") {
doFirst {
println("hiiiiiiiii")
var names2 = "a= "
fileTree("$buildDir\\classes\\kotlin\\main\\tech\\example\\ecommerce\\ecommerce\\controller\\")
.visit {
if (this.file.name != "WebPagesController.class") {
names2 += this.file.path + "\n"
println(file(this.file.path).readText())
}
}
println(names2)
}
})
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
Any hints are welcomed, Thanks in advance
In fileTree("$buildDir\\classes\\kotlin\\main\\tech\\example\\ecommerce\\ecommerce\\controller\\")
using projectDir instead of buildDir with syntax
fileTree("$projectDir/src/main/kotlin/tech/example/ecommerce/ecommerce/controller") s

error when import kotlin project android studio 3.5.3

I try to import project
i get this error when import project in android studio 3.5.3
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
and this error
This version of Android Studio cannot open this project, please retry with Android Studio 3.6 or newer
import org.jetbrains.kotlin.config.KotlinCompilerVersion
plugins {
id("com.android.application")
kotlin("android")
kotlin("kapt")
}
// https://stackoverflow.com/a/52441962
fun String.runCommand(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS
): String? = try {
ProcessBuilder("\\s".toRegex().split(this))
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start().apply { waitFor(timeoutAmount, timeoutUnit) }
.inputStream.bufferedReader().readText()
} catch (e: java.io.IOException) {
e.printStackTrace()
null
}
android {
compileSdkVersion(29)
buildToolsVersion("29.0.2")
viewBinding.isEnabled = true
val gitVersion = listOf(
"git rev-parse --abbrev-ref HEAD",
"git rev-list HEAD --count",
"git rev-parse --short HEAD"
).joinToString("-") { it.runCommand()?.trim() ?: "" } +
(if (("git status -s".runCommand() ?: "").isBlank()) "" else "-dirty")
defaultConfig {
applicationId = "com.test.cale"
minSdkVersion(15)
targetSdkVersion(29)
versionCode = 621
versionName = "6.2.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
resConfigs("en", "fa", "ckb", "ar", "ur", "ps", "glk", "azb", "ja")
setProperty("archivesBaseName", "PersianCalendar-$versionName-$gitVersion")
}
signingConfigs {
create("nightly") {
storeFile = rootProject.file("nightly.keystore")
storePassword = "android"
keyAlias = "androiddebugkey"
keyPassword = "android"
}
}
buildTypes {
create("nightly") {
signingConfig = signingConfigs.getByName("nightly")
versionNameSuffix = "-${defaultConfig.versionName}-$gitVersion-nightly"
applicationIdSuffix = ".nightly"
isMinifyEnabled = true
isShrinkResources = true
}
getByName("debug") {
versionNameSuffix = "-${defaultConfig.versionName}-$gitVersion"
applicationIdSuffix = ".debug"
}
getByName("release") {
isMinifyEnabled = true
isShrinkResources = true
// Maybe proguard-android-optimize.txt in future
// setProguardFiles(listOf(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"))
}
}
}
dependencies {
implementation(project(":equinox"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${KotlinCompilerVersion.VERSION}")
implementation("androidx.appcompat:appcompat:1.1.0")
implementation("androidx.preference:preference-ktx:1.1.0")
implementation("androidx.recyclerview:recyclerview:1.1.0")
implementation("androidx.cardview:cardview:1.0.0")
implementation("androidx.viewpager2:viewpager2:1.0.0")
implementation("com.google.android.material:material:1.1.0-rc02")
implementation("com.google.android:flexbox:1.1.0")
implementation("com.google.android.apps.dashclock:dashclock-api:2.0.0")
val navVersion = "2.1.0"
implementation("androidx.navigation:navigation-fragment-ktx:$navVersion")
implementation("androidx.navigation:navigation-ui-ktx:$navVersion")
implementation("androidx.core:core-ktx:1.1.0")
implementation("androidx.fragment:fragment-ktx:1.1.0")
implementation("androidx.activity:activity-ktx:1.0.0")
implementation("androidx.browser:browser:1.0.0")
implementation("androidx.work:work-runtime-ktx:2.2.0")
// debugImplementation("com.squareup.leakcanary:leakcanary-android:2.0-alpha-2")
// debugImplementation("com.github.pedrovgs:lynx:1.1.0")
testImplementation("junit:junit:4.12")
androidTestImplementation("androidx.test:runner:1.2.0")
androidTestImplementation("androidx.test:rules:1.2.0")
androidTestImplementation("androidx.test.espresso:espresso-contrib:3.2.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")
}
please resolve the problem
Top-level Project Gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.6.0-rc01")
classpath(kotlin("gradle-plugin", version = "1.3.61"))
}
}
allprojects {
repositories {
google()
jcenter()
maven("https://jitpack.io")
}
}
task("clean") {
delete(rootProject.buildDir)
}

How to configure ssl using KTOR library?

I'm looking for a way to configure https for Ktor application.
I've found an official documentation there:
https://ktor.io/servers/self-signed-certificate.html
Here explained how to add links to certs inside the HOCON config file.
Is it possible to config ssl without config file?
Here's my codebase:
http = embeddedServer(Netty, port = listenPort, configure = {
connectionGroupSize = 1
workerGroupSize = 5
}){
if(sslCertificate != null) {
install(HttpsRedirect) {
sslPort = 443
}
}
install(StatusPages) {
exception<NotFoundError> { cause ->
logger.error("NotFoundError:", cause.message)
call.respondText(cause.message ?: "",
ContentType.Text.Plain, HttpStatusCode.NotFound){}
}
exception<BadFormatError> { cause ->
logger.error("BadFormatError:", cause.message)
call.respondText(cause.message ?: "",
ContentType.Text.Plain, HttpStatusCode.BadRequest){}
}
exception<UserMistake> { cause ->
logger.error("UserMistake:", cause.message)
call.respondText(cause.message ?: "",
ContentType.Text.Plain, HttpStatusCode.BadRequest){}
}
exception<OverloadedException> { cause ->
logger.error("OverloadedException:", cause.message)
call.respondText(cause.message ?: "",
ContentType.Text.Plain, HttpStatusCode.ServiceUnavailable){}
}
exception<Exception> { cause ->
logger.error("Exception:", cause.message)
call.respondText(cause.message ?: "",
ContentType.Text.Plain, HttpStatusCode.InternalServerError){}
}
}
intercept(ApplicationCallPipeline.Call) {
call.response.headers.append(HttpHelper.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
call.response.headers.append(HttpHelper.ACCESS_CONTROL_REQUEST_METHOD, "POST, GET, OPTIONS")
// call.response.headers.append(HttpHelper.CONTENT_TYPE, "application/json")
if(call.request.uri.endsWith("/")) {
call.respondRedirect(call.request.uri.dropLast(1))
}
}
}
http.start()
It's a bit complex, but possible. You configure this using sslConnector in the environment:
fun main() {
val environment = applicationEngineEnvironment {
log = LoggerFactory.getLogger("ktor.application")
// Here you can the key store and keys configuration
sslConnector(keyStore, ...)
module(Application::myModule)
}
embeddedServer(Netty, environment, configure = {
// ...
})
}
fun Application.myModule() {
}

React Native build error: Text must not be null or empty

My Jenkins build has given me the following error:
13:18:22 FAILURE: Build failed with an exception.
13:18:22
13:18:22 * Where:
13:18:22 Script '/Users/abcd/Jenkins/Jenkins-Workspaces/ABCD/ABCDL/node_modules/#react-native-community/cli-platform-android/native_modules.gradle' line: 190
13:18:22
13:18:22 * What went wrong:
13:18:22 A problem occurred evaluating settings 'AppName'.
13:18:22 > Text must not be null or empty
13:18:22
It seems the problem is with the #react-native-community/cli-platform node module, but reading over this closed issue:
https://github.com/facebook/react-native/issues/25479
its unclear to me what exactly is the proposed and final solution to this.
There is a recommendation on a fix that is more straightforward in this react-native issue:
https://github.com/facebook/react-native/issues/25822
but my error is not complaining about that line.
As far as installing #react-native-community/cli I believe I already have it inside my package-lock.json file:
"react-native": {
"version": "0.60.4",
"resolved": "https://registry.npmjs.org/react-native/-/react-native-0.60.4.tgz",
"integrity": "sha512-WE41lbGQjnzM9srIFtMDtMJkQAvk95iZwuFvAxl68s80bkYa7Ou9sGFHpeYIV6cY8yHtheCSo5q6YMxhdfkdOw==",
"requires": {
"#babel/runtime": "^7.0.0",
"#react-native-community/cli": "^2.0.1",
"#react-native-community/cli-platform-android": "^2.0.1",
"#react-native-community/cli-platform-ios": "^2.0.1",
Others mentioned something about app/build.gradle, here is the relevant part of mine:
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Mention was also made of android/settings.gradle, this one is mine:
rootProject.name = 'NFIBEngage'
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':appcenter-crashes'
project(':appcenter-crashes').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-crashes/android')
include ':appcenter-analytics'
project(':appcenter-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-analytics/android')
include ':appcenter'
project(':appcenter').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter/android')
include ':react-native-webview'
project(':react-native-webview').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview/android')
apply from: file("../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
From what I have gathered here:
https://react-native-community.github.io/upgrade-helper/?from=0.53.3&to=0.60.4
The above files are correct.
So what exactly is wrong here and how do I fix it?
In terms of node_modules/#react-native-community/cli-platform-android/native_modules.gradle line 190 is this one:
def json = new JsonSlurper().parseText(reactNativeConfigOutput)
Could the problem be with how I wrote index.js file:
/**
* #format
*/
import { AppRegistry } from "react-native";
// old config code
import KeyboardManager from "react-native-keyboard-manager";
// old config code ^^^
import NFIBEngage from "./App";
import { name as appName } from "./app.json";
// old config code
import { Sentry } from "react-native-sentry";
Sentry.config(
"https://asdf#sentry.io/123456677"
).install();
KeyboardManager.setToolbarPreviousNextButtonEnable(true);
// old config code ^^^
AppRegistry.registerComponent("NFIBEngage", () => NFIBEngage);
Is AppRegistry.registerComponent() written correctly?
I ran the Jenkins script locally, which I believe is this script right here:
import fs from "fs-extra";
import eachSeries from "async/eachSeries";
import { exec } from "child_process";
import { androidDirectory } from "../../app.json";
import { resolveFromRoot, distDir, createLogger } from "../build";
const logger = createLogger("android");
const APK_PATTERN = /release\.apk$/i;
function copyArtifactsToDist() {
logger.logHeader("Copying APK to Dist", { repeatChar: "=" });
const baseDir = `${androidDirectory}/app/build/outputs/apk`;
const allFlavs = ["dev", "qa", "ua", "prod"];
const branchName = process.env.GitVersion_BranchName || "";
const buildFlavour = branchName.startsWith("release/") ? allFlavs : ["dev"];
const envs = {
dev: "INT",
qa: "QA",
ua: "UA",
prod: ""
};
buildFlavour
.map(env => {
const apkOutputDir = resolveFromRoot(`${baseDir}/${env}/release`);
return {
apkOutputDir,
env
};
})
.forEach(({ apkOutputDir, env }) => {
const src = `${apkOutputDir}/app-${env}-release.apk`;
//prettier-ignore
const binaryName = env === 'prod' ? 'ENGAL.apk' : `ENGAL-${envs[env]}.apk`;
const dest = `${distDir}/${binaryName}`;
fs.copy(src, dest, (err: Error) => {
if (err) {
logger.error(err);
}
});
});
}
function run() {
logger.logHeader("Starting Android Builds", { repeatChar: "#" });
const flavours = [
{
endpoint: "dv",
flavour: "Dev",
appcenterKey: "<hashKeys>"
},
{
endpoint: "qa",
flavour: "Qa",
appcenterKey: "<hashKeys>"
},
{
endpoint: "ua",
flavour: "Ua",
appcenterKey: "<hashKeys>"
},
{
endpoint: "prod",
flavour: "Prod",
appcenterKey: "<hashKeys>"
}
];
const versionCode = process.env.Build || 1;
const release = process.env.GitVersion_MajorMinorPatch || "1.0.0";
const fullAppVersion = `${release}-${versionCode}`;
const devFlav = flavours.find(f => f.flavour.toLocaleLowerCase() === "dev");
const branchName = process.env.GitVersion_BranchName || "";
const buildFlavour = branchName.startsWith("release/") ? flavours : [devFlav];
eachSeries(
buildFlavour,
(f, callback) => {
//prettier-ignore
logger.logHeader(
`starting gradle assemble${f.flavour}Release with flag - versionName=${fullAppVersion} -PversionCode=${versionCode}`,
{repeatChar: '-'}
);
const engaInfo = `ENGAGE_VERSION=${fullAppVersion}`;
const engaEndpoint = `ENGAGE_ENDPOINT=${f.endpoint}`;
const engaCenter = `APPCENTER_KEY=${f.appcenterKey}`;
const engaPlatform = "APPCENTER_PLATFORM=android";
//prettier-ignore
const prepare = `${engaEndpoint} ${engaCenter} ${engaInfo} ${engaPlatform} npm run setup`;
const cd = `cd ${androidDirectory}`;
//prettier-ignore
const releaseCmd = `./gradlew assemble${f.flavour}Release -PversionName=${fullAppVersion} -PversionCode=${versionCode} && cd ..`;
exec(`${prepare} && ${cd} && ${releaseCmd}`, err => {
if (err) {
return callback(err);
}
logger.logHeader(`${f.flavour} Android Build Successful!`, {
repeatChar: "#"
});
logger.close();
callback(null);
});
},
error => {
if (error) {
logger.logHeader("Android Builds Failed!", {
repeatChar: "#"
});
logger.error(error);
logger.close();
}
copyArtifactsToDist();
}
);
}
run();
via npm run build and locally I got this error:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'assembleDevRelease' not found in root project 'AppName'. Some candidates are: 'assembleRelease'.
Are these related errors? Anyone experienced with React Native builds?
As suggested, I looked into my android/app/build.gradle file for productFlavors and noticed that indeed they were missing between here:
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 123456 + defaultConfig.versionCode
}
}
}
So I added it like so:
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
productFlavors {
dev {
resValue "string", "app_name", getAppName("INT")
resValue "string", "link_launcher", getLauncher("dv")
applicationIdSuffix ".dv"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
qa {
resValue "string", "app_name", getAppName("QA")
resValue "string", "link_launcher", getLauncher("qa")
applicationIdSuffix ".qa"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
ua {
resValue "string", "app_name", getAppName("UA")
resValue "string", "link_launcher", getLauncher("ua")
applicationIdSuffix ".ua"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
prod {
resValue "string", "app_name", getAppName()
resValue "string", "link_launcher", getLauncher()
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "601125149914"]
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
The buildTypes is looking a bit different than the original legacy buildTypes so I am not sure if that's okay, but at any rate I then ran npm run build again locally and got this error:
* Where:
Build file '/Users/danale/Projects/NFIBEngage/android/app/build.gradle' line: 168
* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method getAppName() for arguments [INT] on ProductFlavor_Decorated{name=dev, dimension=null, minSdkVersion=null, targetSdkVersion=null, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=null, versionName=null, applicationId=null, testApplicationId=null, testInstrumentationRunner=null, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null, signingConfig=null, resConfig=null, mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={}, mWearAppUnbundled=null} of type com.android.build.gradle.internal.dsl.ProductFlavor.
I was able to resolve the local error by adding the missing methods like so:
def appName = "Engage";
/**
* Get the version name from command line param
*
* #return int If the param -PversionName is present then return int value or -1
*/
def getAppName = { env ->
return (env ? appName + " ("+ env + ")" : appName);
}
/**
* Get the version name from command line param
*
* #return int If the param -PversionName is present then return int value or -1
*/
def getLauncher = { env ->
return (env ? "engage-" + env + ".nfib.org" : "engage.nfib.org");
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions "default"
defaultConfig {
applicationId "com.nfib.engage"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
productFlavors {
dev {
dimension 'default'
resValue "string", "app_name", getAppName("INT")
resValue "string", "link_launcher", getLauncher("dv")
applicationIdSuffix ".dv"
manifestPlaceholders = [onesignal_app_id: "b78285eb-f1ec-46f3-9ad0-c7efe691a401",
onesignal_google_project_number: "584236827312"]
}
qa {
dimension 'default'
resValue "string", "app_name", getAppName("QA")
resValue "string", "link_launcher", getLauncher("qa")
applicationIdSuffix ".qa"
manifestPlaceholders = [onesignal_app_id: "e4280f5e-62ec-41a4-bd86-f5b94e471a36",
onesignal_google_project_number: "162802054510"]
}
ua {
dimension 'default'
resValue "string", "app_name", getAppName("UA")
resValue "string", "link_launcher", getLauncher("ua")
applicationIdSuffix ".ua"
manifestPlaceholders = [onesignal_app_id: "2ffd8dc0-9c6b-4035-999d-fc694194725a",
onesignal_google_project_number: "594905904045"]
}
prod {
dimension 'default'
resValue "string", "app_name", getAppName()
resValue "string", "link_launcher", getLauncher()
manifestPlaceholders = [onesignal_app_id: "82dcb42f-1d35-4b79-bc28-2d1d02dbda36",
onesignal_google_project_number: "601125149914"]
}
}
Unfortunately, I continue to get the same error in Jenkins.
Some of the changes to get the build working, from comments:
From your package.json, your cli version is at ^2.0.1 and 2.0.1 is indeed the version of the cli that had the issue you linked to from github.com/facebook/react-native/issues/25479 Have you verified that the line similar to def command = "../node_modules/.bin/react-native config" (from github.com/facebook/react-native/issues/…) in your node_modules/#react-native-community/cli-platform-android/native_modules.gradle is correct? You should also ensure your installed version of the cli is >= 2.0.2.
Make sure your buildTypes and productFlavors definitions in android/app/build.gradle are set up to include all the different variants you are trying to build in your jenkins job. Looks like you have flavors for dev, qa, ua and prod. Check out the gradle docs developer.android.com/studio/build/build-variants#build-types for more info.
Looks like you're missing a getAppName function in your build.gradle. Something like ext.getAppName = {suffix = '' -> 'MyAppName' + suffix}. A quick scan of your build.gradle looks like you need another called getLauncher which returns an appropriate string for whatever you use link_launcher for.
I upgraded my node version on my CI tool and fixed this exact error.
I was previously on version 6 and bumped it to 10
I have also face this problem
very easy solution for this problem
Remove node_module
and
Reinstall node_module : npm install
react-native run-android

Cause: org.gradle.api.internal.artifacts.DefaultModuleVersionSelector

cant import gradle project in intellij idea
Cause: org.gradle.api.internal.artifacts.DefaultModuleVersionSelector
I couldn't build the project through terminal also.Error in terminal is:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':commons:compileJava'.
Compilation failed;
gradle file:
buildscript {
repositories {
mavenCentral()
// maven { url "${artifactoryRepoUrl}" }
jcenter()
} ext {
springBootVersion = '1.4.2.RELEASE'
commonsVersion = '0.4.3'
recruiterVersion = '0.2.6'
jobseekerVersion = '0.1.9'
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4+"
}
}
subprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'maven'
apply plugin: 'org.springframework.boot'
apply plugin: 'maven-publish'
repositories {
mavenLocal()
mavenCentral()
// maven { url "${artifactoryRepoUrl}" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext {
springCloudVersion = '1.1.2.RELEASE'
springSecurityVersion = '4.1.1.RELEASE'
springRedisVersion = '1.7.2.RELEASE'
jedisVersion = '2.7.2'
log4jVersion = '2.6.2'
jacksonVersion = '2.8.1'
apacheCommonsVersion = '2.4.2'
lombokVersion = '1.16.10'
jnaVersion = '3.0.9'
jestVersion = '2.0.3'
beanutilsVersion = '1.9.2'
jwtVersion = '0.6.0'
springAWSVersion = '1.1.0.RELEASE'
mysqlConnectorVersion = '6.0.3'
springJDBCVersion = '4.3.2.RELEASE'
dbcpVersion = '2.1.1'
springCloudAWSVersion = '1.0.4.RELEASE'
elasticClientVersion = '5.0.2'
swaggerVersion = '2.4.0'
jose4jVersion = '0.5.4'
}
configurations.all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'logback-classic'
}
}
try changing gradle file like :
buildscript {
ext {
springBootVersion = '1.4.2.RELEASE'
commonsVersion = '0.4.3'
recruiterVersion = '0.2.6'
jobseekerVersion = '0.1.9'
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4+"
}
}
subprojects {
...
Try to remove the following line:
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4+"