A problem occurred evaluating project ':tflite' - java

I try to use tflite package to create a live object detection app, but it seems that after i installed both the packages : tflite and camera, and also writing the detection code it doesn't seem to run .
Packages :
Tflite : https://pub.dev/packages/tflite
Camera : https://pub.dev/packages/camera
this error occure :
A problem occurred evaluating project ':tflite'.
The entire Error :
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\Hepha\Documents\flutter_windows_2.10.3-stable\flutter\.pub-cache\hosted\pub.dartlang.org\tflite-1.1.2\android\build.gradle' line: 24
* What went wrong:
A problem occurred evaluating project ':tflite'.
> No signature of method: build_a7q9josm4oau2t0m3mow48bac.android() is applicable for argument types: (build_a7q9josm4oau2t0m3mow48bac$_run_closure2) values: [build_a7q9josm4oau2t0m3mow48bac$_run_closure2#c7c7456]
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1m 43s
Running Gradle task 'assembleDebug'... 104,7s|Exception: Gradle task assembleDebug failed with exit code 1
My pubspec.yaml file :
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
camera: ^0.9.4+1
image_picker: ^0.8.4+11
tflite: ^1.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/
- assets/labels.txt
- assets/metadata_V2.tflite
My android/app/build.gradle file :
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.aiassistantapp"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 21
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
aaptOptions {
noCompress 'tflite'
noCompress 'lite'
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
Can anyone help me please ? thank you

So first, to get rid of this error you should
change this on
~\tflite-1.1.2\android\build.gradle:
dependencies {
compile 'org.tensorflow:tensorflow-lite:+'
compile 'org.tensorflow:tensorflow-lite-gpu:+'
}
to this:
dependencies {
implementation 'org.tensorflow:tensorflow-lite:+'
implementation 'org.tensorflow:tensorflow-lite-gpu:+'
}
Just change compile to implementation based on that github issue in tflite to solve the issue that you post above.
for me it worked as a charm, but when I try to infer my models with some images, this error emerged
Caused by: java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite tensor with type UINT8 and a Java object of type [[F (which is compatible with the TensorFlowLite type FLOAT32).
and the whole application crash.
So if your model image based so check this answer its related to quantization of model when you export yours.
Just do this:
config = QuantizationConfig.for_float16()
model.export(export_dir='.', tflite_filename='model_fp16.tflite', quantization_config=config)
hope this works for you!

Related

React Native Task error ':app:processDebugMainManifest FAILED'

I recently upgraded React Native 0.63.4 to 0.70.1 and have been trying to iron everything out re upgrading packages and dependencies etc.
I'm really stuck on this particular error and can't seem to find a solution.
The command prompt says:
Task :app:processDebugMainManifest FAILED
...
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
What went wrong:
Execution failed for task ':app:processDebugMainManifest'.
com.android.manifmerger.ManifestMerger2$MergeFailureException: org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 6; The processing instruction target matching "[xX][mM][lL]" is not allowed.
2: Task failed with an exception.
What went wrong:
java.lang.StackOverflowError (no error message)
I haven't been able to find a solution online apart from adding the line
'org.gradle.jvmargs=--add-opens java.base/java.io=ALL-UNNAMED' to my android/gradle.properties file, which hasn't worked.
The issue that I had directly before this error was:-
Command prompt:
FAILURE: Build failed with an exception.
What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
Could not find org.webkit:android-jsc:r245459.
Required by:
project :app
I resolved this by changing 'def jscFlavor = 'org.webkit:android-jsc:r245459'' to 'def jscFlavor = 'org.webkit:android-jsc:r250230'' in my android/app/build.gradle file, as I noticed that my 'node-modules/jsc-android/dist/org/webkit/android-jsc' file contained an r250230 file rather than an r245459 one. I'm not sure whether changing this manually has cause the most recent error.
Here's my android/app/build.gradle file:
apply plugin: "com.android.application"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://reactnative.dev/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
enableHermes: false
]
// MANUALLY REMOVED:
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
// apply from: "../../node_modules/react-native/react.gradle"
// apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
// apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"
//
// ADDED:
// apply from: new File(["node", "--print", "require.resolve('expo-modules-core/package.json')"].execute(null, rootDir).text.trim(), "../gradle.groovy")
apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle")
apply from: new File(["node", "--print", "require.resolve('expo-updates/package.json')"].execute(null, rootDir).text.trim(), "../scripts/create-manifest-android.gradle")
//
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
// Original:
// def jscFlavor = 'org.webkit:android-jsc:+'
// ***BUG FIX*** Specific version:
// def jscFlavor = 'org.webkit:android-jsc:r245459'
// ADDED NEW Specific version (?) found in (node-modules > jsc-android > dist > org > webkit > android-jsc > r250230):
def jscFlavor = 'org.webkit:android-jsc:r250230'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false)
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.personalchef"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
// ADDED:
manifestPlaceholders = [
'appAuthRedirectScheme': 'host.exp.exponent'
]
//
}
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://reactnative.dev/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) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
implementation project(':react-native-fs')
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
addUnimodulesDependencies()
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/"
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// 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) {
// ORIGINAL:
// from configurations.compile
// into 'libs'
// MANUALLY ADDED:
from configurations.implementation
into 'libs'
}
// MANUALLY REMOVED:
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
//
// ADDED:
// apply from: new File(["node", "--print", "require.resolve('#react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
// applyNativeModulesAppBuildGradle(project)
//
My android/build.gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
// MANUALLY REMOVED:
// buildToolsVersion = "29.0.3"
// minSdkVersion = 21
// compileSdkVersion = 30
// targetSdkVersion = 30
//
// MANUALLY ADDED:
buildToolsVersion = "31.0.0"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31
if (System.properties['os.arch'] == "aarch64") {
// For M1 Users we need to use the NDK 24 which added support for aarch64
ndkVersion = "24.0.8215888"
} else {
// Otherwise we default to the side-by-side NDK version from AGP.
ndkVersion = "21.4.7075529"
}
//
}
repositories {
google()
// MANUALLY REMOVED:
// jcenter()
//
// ADDED MANUALLY:
mavenCentral()
//
}
dependencies {
// MANUALLY REMOVED:
// classpath("com.android.tools.build:gradle:4.1.0")
//
// MANUALLY ADDED:
classpath("com.android.tools.build:gradle:7.2.1")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("de.undercouch:gradle-download-task:5.0.1")
//
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
// MANUALLY REMOVED:
// mavenLocal()
//
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
// ADDED MANUALLY:
mavenCentral {
// We don't want to fetch react-native from Maven Central as there are
// older versions over there.
content {
excludeGroup "com.facebook.react"
}
}
//
// MANUALLY REMOVED:
// jcenter()
//
maven { url 'https://www.jitpack.io' }
}
}
My android/settings.gradle file:
rootProject.name = 'PersonalChef'
// MANUALLY REMOVED:
// apply from: file("../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
//
// MANUALLY REMOVED:
// apply from: new File(["node", "--print", "require.resolve('expo-modules-core/package.json')"].execute(null, rootDir).text.trim(), "../gradle.groovy");
// includeUnimodulesProjects()
// ADDED:
apply from: '../node_modules/react-native-unimodules/gradle.groovy'; includeUnimodulesProjects()
apply from: new File(["node", "--print", "require.resolve('#react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesSettingsGradle(settings)
//
include ':app'
includeBuild('../node_modules/react-native-gradle-plugin')
if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") {
include(":ReactAndroid")
project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid')
include(":ReactAndroid:hermes-engine")
project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine')
}
Thank you in advance if you're able to help.
I've been struggling with this kind of errors for several days and there're a lot of post to read about out there.
My suggestion is to create a new RN project and test that everything is okay. I mean without anything added and test all your Gradle's commands. Then, if you see that your Gradle's files are fine, start adding the rest of your code. First, start adding all the necessary packages and test all again. And finally, add the code files itself.
In case this helps anyone, I fixed this bug using the most popular answer (from user kjhughes) on this post:
Error: The processing instruction target matching "[xX][mM][lL]" is not allowed
I Ctrl F'd <?xml ?> in my main project folder, went through each file that returned an instance from the search and found a couple of files where the declaration wasn't at the very top of the file, so I moved it top the top.
Hope this helps!

Error while running Fortify on Gradle 7.2 project

I am getting an error while running Fortify 20 on a Gradle-Java Project. The project compiles smoothly with "gradle build" command, but when running Fortify I get this error:
Must not use executable property on ForkOptions together with javaCompiler property
The only clue I have is that this functionality was introduced since version 6.7 but the project was built on gradle 7.
I wonder if it is possible to inhibit one of the 2 things causing the error?
Looks like it might be related to Gradle.
https://github.com/gradle/gradle/blob/master/subprojects/language-java/src/main/java/org/gradle/api/tasks/compile/JavaCompile.java
If you look at the github code, you will see this method:
private void validateConfiguration() {
if (javaCompiler.isPresent()) {
checkState(getOptions().getForkOptions().getJavaHome() == null, "Must not use `javaHome` property on `ForkOptions` together with `javaCompiler` property");
checkState(getOptions().getForkOptions().getExecutable() == null, "Must not use `executable` property on `ForkOptions` together with `javaCompiler` property");
}
}
validateConfiguration() is called from createSpec() which is run during compile().
Please see example build.gradle below which uses java plugin and compileJava task, and options.forkOptions.executable:
https://docs.gradle.org/current/userguide/java_plugin.html#java_plugin
import com.nr.builder.JarUtil
apply plugin: 'java'
subprojects {
dependencies {
// introspector classes for testing externals
testImplementation(project(":instrumentation-test"))
}
}
ext.moduleName = "com.greetings"
dependencies {
implementation("junit:junit:4.13")
}
compileJava {
inputs.property("moduleName", "com.greetings")
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
'--patch-module', "$moduleName=" + files(sourceSets.main.java.srcDirs).asPath,
]
classpath = files()
}
}
compileJava.options.encoding = 'UTF-8'
compileJava.options.fork = true
// Compile with Java 11 to test module support
compileJava.options.forkOptions.executable = jdk11 + '/bin/javac'
compileJava.options.forkOptions.javaHome = new File(jdk11)
compileTestJava.options.encoding = 'UTF-8'
compileTestJava.options.fork = true
// Compile with Java 11 to test module support
compileTestJava.options.forkOptions.executable = jdk11 + '/bin/javac'
compileTestJava.options.forkOptions.javaHome = new File(jdk11)
// Boot classpath no longer works in JDK 9+ so we should ignore it here
compileJava.options.bootstrapClasspath = null
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
def module_test_args = [
"-javaagent:${project.jar.archivePath.absolutePath}",
"-javaagent:${JarUtil.getNewRelicJar(project(":newrelic-agent")).absolutePath}",
"-Dnewrelic.config.file=${project(':newrelic-agent').projectDir}/src/test/resources/com/newrelic/agent/config/newrelic.yml",
"-Dnewrelic.unittest=true",
"-Dnewrelic.config.startup_log_level=warn",
"-Dnewrelic.debug=$newrelicDebug",
"--module-path=lib:out/production/classes",
"--add-modules com.greetings",
"--module junit/org.junit.runner.JUnitCore"
]
test {
dependsOn(project(":newrelic-agent").getTasksByName("newrelicJar", false))
forkEvery = 1
maxParallelForks = Runtime.runtime.availableProcessors()
executable = jdk11 + '/bin/java'
minHeapSize = "256m"
maxHeapSize = "256m"
beforeSuite {
descriptor ->
// We get two notifications per Test class. One of them is simply the Gradle executor used to run the test
// We filter that one out and only log the Test class name with this null check.
if (descriptor.getClassName() != null) {
logger.lifecycle("Running test suite: " + descriptor.getClassName())
}
}
}
javadoc {
onlyIf { JavaVersion.current().isJava11Compatible() }
}
If you want to keep using the Gradle toolchain feature, add the following to your build.gradle:
// Circumvents issues with Fortify scan without disabling Gradle toolchain feature
tasks.withType(JavaCompile).configureEach {
doFirst {
configure(options) {
configure(forkOptions) {
executable = null
javaHome = null
}
}
}
}

How to pass -np argument to MPJ in gradle?

I was trying to do something with MPJ Express(My home work)
and i couldn't find how to pass -np argument to MPJRun.
group 'ST1'
version '1.0-SNAPSHOT'
apply plugin: 'application'
mainClassName = 'example.Main'
sourceCompatibility = 1.8
def mpjHome = System.getenv( 'MPJ_HOME')
def mpjStarter = files("$mpjHome/lib/starter.jar")
def mpjJar = files("$mpjHome/lib/mpj.jar ")
def mpjClasspath = sourceSets.main.runtimeClasspath - mpjJar
dependencies {
compile mpjJar
}
run{
main = 'runtime.starter.MPJRun'
classpath = mpjStarter
args '-np 2' ,mainClassName, '-cp' , mpjClasspath.asPath
dependsOn classes
}
Your args line should looks like:
args '-np', 2 ,mainClassName, '-cp' , mpjClasspath.asPath
movie which shows config in gradle: https://www.youtube.com/watch?v=gj-3Td6ZOyc&t=942s

Maven-publish cannot not apply withXML on pom file (No signature of method)

Ok, so I am having the exact issue as described here:
Android library dependencies missing from POM with Gradle
I copied the provided answer to my gradle file as follows:
publishing {
publications {
mavenAar(MavenPublication) {
groupId group
artifactId 'exampleId'
version version
artifact source: file('build/outputs/aar/example-release.aar')
//The publication doesn't know about our dependencies, so we have to manually add them to the pom
pom.withXml {
// for dependencies and exclusions
def dependenciesNode = asNode().appendNode('dependencies')
configurations.compile.allDependencies.each { ModuleDependency dp ->
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', dp.group)
dependencyNode.appendNode('artifactId', dp.name)
dependencyNode.appendNode('version', dp.version)
// for exclusions
if (dp.excludeRules.size() > 0) {
def exclusions = dependencyNode.appendNode('exclusions')
dp.excludeRules.each { ExcludeRule ex ->
def exclusion = exclusions.appendNode('exclusion')
exclusion.appendNode('groupId', ex.group)
exclusion.appendNode('artifactId', ex.module)
}
}
}
}
}
}
repositories {
mavenLocal()
maven {
url selectDeploymentURL()
if ( project.hasProperty( 'nexusUser' ) ) {
credentials {
username project.getProperty('nexusUser')
password project.getProperty('password')
}
}
}
}
}
However I am getting an error when attempting to publishToMavenLocal, and I'm not sure why?
FAILURE: Build failed with an exception.
* Where:
Build file 'path/build.gradle' line: 136
* What went wrong:
Execution failed for task ':example:generatePomFileForMavenAarPublication'.
> Could not apply withXml() to generated POM
> No signature of method: build_42xq5bsii69isvukzktk1oy51$_run_closure5_closure19_closure21_closure23_closure24.doCall() is applicable for argument types: (org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated) values: [org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated#433edba9]
Possible solutions: doCall(org.gradle.api.artifacts.ModuleDependency), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object)
Note: Line 136 is this line:
configurations.compile.allDependencies.each { ModuleDependency dp ->
So as Karma has it, I found the answer shortly after posting
I just removed the ModuleDependency dp and referred to everything from it, and it got past this error, I see the new nodes in the pom file now.
configurations.compile.allDependencies.each {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
The root cause of the crash is that not all dependencies are ModuleDependency objects. Something like the following should fix the problem and lets you still add exclusions (which aren't on the base class).
configurations.compile.allDependencies.each { dp ->
if (dp instanceof ModuleDependency) {
// do stuff
}
}
Compile is deprecated we have to use implementation.
for Example
configurations.implementation.allDependencies.each {
if(it.group != null && (it.name != null || "unspecified".equals(it.name)) && it.version != null)
{
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
}
}

Android new build system (gradle) and aspectj

In Google IO the new build system gradle is announced to replace ant.
My project is using aspectj and I would like to use it in my project.
I couldn't figure out some variables to get it working. I don't find android.* output classpath there. Anyone can help?
Here is my current build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
sourceCompatibility = 1.6
configurations {
ajc
}
dependencies {
compile fileTree(dir: 'libs', includes: ['*.jar'])
ajc files('build-tools/aspectjtools.jar', 'libs/aspectjrt.jar')
}
android {
compileSdkVersion 16
buildToolsVersion "17"
defaultConfig {
minSdkVersion 8
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
instrumentTest.setRoot('test')
}
}
gradle.projectsEvaluated {
compileJava.doLast {
tasks.compileAspectJ.execute()
}
println 'lalalalala'
}
task compileAspectJ {
ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties",
classpath: configurations.ajc.asPath)
ant.iajc(source: sourceCompatibility, target: sourceCompatibility,
destDir: "?????????????????????",
classpath: "????????????????????????????") {
sourceroots{
android.sourceSets.main.java.srcDirs.each {
pathelement(location: it.absolutePath)
}
}
}
}
This is the old ant code that works very well:
http://code.google.com/p/anymemo/source/browse/custom_rules.xml
Edit:
Updated the build.gradle according to the first answer.However I the iajc does not seem to recognize all the libraries and complain the classes in the libraries not found
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
sourceCompatibility = 1.6
targetCompatibility = 1.6
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.0"
defaultConfig {
minSdkVersion 9
targetSdkVersion 16
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
configurations {
ajc
aspects
ajInpath
}
ext.aspectjVersion = '1.7.3'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
ajc "org.aspectj:aspectjtools:${aspectjVersion}"
compile "org.aspectj:aspectjrt:${aspectjVersion}"
compile 'com.android.support:appcompat-v7:18.0.0'
}
android.applicationVariants.all { variant ->
variant.javaCompile.doLast {
def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar"
println 'AAAAAAAAAAAAAAAAA: ' + androidSdk
def iajcClasspath = configurations.compile.asPath + ":" + androidSdk
configurations.compile.dependencies.each { dep ->
if(dep.hasProperty("dependencyProject")) {
iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar"
}
}
println 'BBBBBBBBBBBBBB : ' + iajcClasspath
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc (
source:sourceCompatibility,
target:targetCompatibility,
destDir:"${project.buildDir}/classes/${variant.dirName}",
maxmem:"512m",
fork:"true",
aspectPath:configurations.aspects.asPath,
inpath:configurations.ajInpath.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",
classpath:iajcClasspath
){
sourceroots{
android.sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
pathelement(location:"${project.buildDir}/source/r/${variant.dirName}")
}
}
}
}
Errors:
1 [error] The method onPrepareOptionsMenu(Menu) of type FingerPaint must override or impl[3780/18642]
rtype method
[ant:iajc] public boolean onPrepareOptionsMenu(Menu menu) {
[ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^
[ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:21
2 [error] The method onPrepareOptionsMenu(Menu) is undefined for the type GraphicsActivity
[ant:iajc] super.onPrepareOptionsMenu(menu);
[ant:iajc] ^^^^^^^^^^^
[ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:21
7 [error] The method onOptionsItemSelected(MenuItem) of type FingerPaint must override or implement a
supertype method
[ant:iajc] public boolean onOptionsItemSelected(MenuItem item) {
[ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:22
8 [error] The constructor ColorPickerDialog(FingerPaint, FingerPaint, int) is undefined
[ant:iajc] new ColorPickerDialog(this, this, mPaint.getColor()).show();
[ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:25
4 [error] The method onOptionsItemSelected(MenuItem) is undefined for the type GraphicsActivity
[ant:iajc] return super.onOptionsItemSelected(item);
[ant:iajc] ^^^^^^^^^^^^
[ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:25
8 [error] The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applic
able for the arguments (FingerPaint)
[ant:iajc] SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
[ant:iajc]
EDIT:
This the final build.gradle file that works for my project:
https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820
I also wanted to use aspectj with gradle and Android Studio, and I finally got it working, but I still have some hand-written paths that I'd like to replace with more generic gradle options.
Edit: I replaced every hard-coded absolute paths with gradle based alternatives, so this solution does not depend any more on a given platform or user name. However, it still uses relative paths that could change from an IDE to an other or in further releases of Android Studio.
Also, I'm not really satisfied with the way I find the android.jar.
I first load aspectj:
configurations {
ajc
aspects
ajInpath
}
ext.aspectjVersion = '1.7.3'
dependencies {
compile project(":LibTest")
ajc "org.aspectj:aspectjtools:${aspectjVersion}"
compile "org.aspectj:aspectjrt:${aspectjVersion}"
compile 'com.android.support:appcompat-v7:18.0.0'
}
And I then add a task that will run after the JavaCompile task of the current variant:
android.applicationVariants.all { variant ->
variant.javaCompile.doLast {
def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar"
def iajcClasspath = configurations.compile.asPath + ";" + androidSdk
configurations.compile.dependencies.each { dep ->
if(dep.hasProperty("dependencyProject")) {
iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar"
}
}
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc (
source:sourceCompatibility,
target:targetCompatibility,
destDir:"${project.buildDir}/classes/${variant.dirName}",
maxmem:"512m",
fork:"true",
aspectPath:configurations.aspects.asPath,
inpath:configurations.ajInpath.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",
classpath:iajcClasspath
){
sourceroots{
android.sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
pathelement(location:"${project.buildDir}/source/r/${variant.dirName}")
}
}
}
}
Wherever I use ${variant.dirName}, it will be replaced by either "debug" or "release" according to the current build configuration.
Adding android.jar to the classpath is required to compile Android specific classes, and the line pathelement(location:"${project.buildDir}/source/r/${variant.dirName}") is require to use classes from the auto-generated R.java file.
Edit: The iterations over the project dependencies to build iajcClasspath let you use classes from your libraries projects. configurations.compile.asPath already contains a reference to your apklib (aar file), which is actually a zip containing both the jar and the resources of the library. Iajc doesn't recognize these files as it, but there is a bundle directory containing the classes.jar for your library under the build directory. I use a relative path with "release" hard-coded in it, because the library has a different variant than the main project in my situation, so I can't use ${variant.dirName} here.
Here is the complete build.gradle file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 18
}
}
configurations {
ajc
aspects
ajInpath
}
ext.aspectjVersion = '1.7.3'
dependencies {
compile project(":LibTest")
ajc "org.aspectj:aspectjtools:${aspectjVersion}"
compile "org.aspectj:aspectjrt:${aspectjVersion}"
compile 'com.android.support:appcompat-v7:18.0.0'
}
android.applicationVariants.all { variant ->
variant.javaCompile.doLast {
def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar"
def iajcClasspath = configurations.compile.asPath + ";" + androidSdk
configurations.compile.dependencies.each { dep ->
if(dep.hasProperty("dependencyProject")) {
iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar"
}
}
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc (
source:sourceCompatibility,
target:targetCompatibility,
destDir:"${project.buildDir}/classes/${variant.dirName}",
maxmem:"512m",
fork:"true",
aspectPath:configurations.aspects.asPath,
inpath:configurations.ajInpath.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",
classpath:iajcClasspath
){
sourceroots{
android.sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
pathelement(location:"${project.buildDir}/source/r/${variant.dirName}")
}
}
}
}
I figured out that the AAR can not be used as a jar library in my code. If you are using dependencies like this
compile 'com.android.support:appcompat-v7:18.0.0'
You need to find the jar file and add to the classpath. The following code will do it.
tree = fileTree(dir: "${project.buildDir}/exploded-bundles", include: '**/classes.jar')
tree.each { jarFile ->
iajcClasspath += ":" + jarFile
}
So the whole section would be:
variant.javaCompile.doLast {
// Find the android.jar and add to iajc classpath
def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar"
println 'Android SDK android.jar path: ' + androidSdk
def iajcClasspath = androidSdk + ":" + configurations.compile.asPath
configurations.compile.dependencies.each { dep ->
if(dep.hasProperty("dependencyProject")) {
iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar"
}
}
// handle aar dependencies pulled in by gradle (Android support library and etc)
tree = fileTree(dir: "${project.buildDir}/exploded-bundles", include: '**/classes.jar')
tree.each { jarFile ->
iajcClasspath += ":" + jarFile
}
println 'Classpath for iajc: ' + iajcClasspath
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
For the full example please see the build.gradle for AnyMemo project here:
https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820
Although previous answers scripts works for most of the situations, they doesn't cover some of the problems of using Android with AspectJ and Gradle.
My test was to create a library project that should be used by anyone via mavenCentral or by me as a reference library project, and a test application project. The library project is the one that has all the aspects and the application test was trying to use those aspects.
Giving this as a context, the resulting project structure was:
HEAD-Gradle
---LibraryProject
-------SomeAspects
---TestApplication
-------Uses-SomeAspects
The solutions I found that make it work are:
1- For library projects you must use
libraryVariants.all { variant ->
instead of
android.applicationVariants.all { variant ->
2- The build dir changed for 19.+ build tools of Android, so as it is suggested in one comment (thanks to "WithoutClass"), you have to use the exploded-aar dir instead of exploded-bundles dir in the tree variable definition.
From:
def tree = fileTree(dir: "${project.buildDir}/exploded-bundles", include: '**/classes.jar')
To:
def tree = fileTree(dir: "${project.buildDir}/exploded-aar", include: '**/classes.jar')
3- The final problem I faced when making the integration was that if you have a library project, aspects defined on it were not found on the child project. To solve this you have to add the classes.jar of your custom library to the aspectJ compiler configuration. You can achieve this by adding to the dependencies:
aspects project(":YourLibraryProject")
and it is also needed to make some changes in the script provided in the final of this post.
Right now the best script I can imagine that gives full support for aspectj using even library projects is:
For dependencies:
configurations {
ajc
aspects
ajInpath
}
//Version of aspectj
def aspectjVersion = '1.8.+'
// The dependencies for this project
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
//Your dependencies to a custom library project
compile project(":YourLibraryProject")
aspects project(":YourLibraryProject")
//Aspectj dependencies
ajc "org.aspectj:aspectjtools:${aspectjVersion}"
compile "org.aspectj:aspectjrt:${aspectjVersion}"
}
The compiler running script
android.applicationVariants.all { variant ->
variant.javaCompile.doLast {
// Find the android.jar and add to iajc classpath
def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar"
def iajcClasspath = androidSdk + ":" + configurations.compile.asPath
//This line and the fordward assignations allow the aspects support in the child project from the library project
def customAspectsPath = configurations.aspects.asPath
configurations.compile.dependencies.each { dep ->
if(dep.hasProperty("dependencyProject")) {
iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/${variant.buildType.name}/classes.jar"
customAspectsPath += ":" + dep.dependencyProject.buildDir + "/bundles/${variant.buildType.name}/classes.jar"
}
}
// handle aar dependencies pulled in by gradle (Android support library and etc)
def tree = fileTree(dir: "${project.buildDir}/exploded-aar", include: '**/classes.jar')
tree.each { jarFile ->
iajcClasspath += ":" + jarFile
}
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc (
source:sourceCompatibility,
target:targetCompatibility,
destDir:"${project.buildDir}/classes/${variant.dirName}",
maxmem:"512m",
fork:"true",
aspectPath:customAspectsPath,
inpath:configurations.ajInpath.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",
classpath:iajcClasspath
){
sourceroots{
android.sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
pathelement(location:"${project.buildDir}/source/r/${variant.dirName}")
}
}
}
}
Remember that if you want to run AspectJ on a library-child project, you must have also this script on the build.gradle of the library.
In the case of using Android Studio 0.8 or above, it seems that using gradle 0.12.+ is necessary.
In gradle 0.12.+, exploded aar are extracted in the build folder, not in the exploded-aar folder.
Therefore, in order to handle aar dependencies, you must use this code:
tree = fileTree(dir: "${project.buildDir}", include: '**/classes.jar')
tree.each { jarFile ->
iajcClasspath += ":" + jarFile
}
Another easier way to set things up is using the android aspectj plugin which is better maintained.
https://github.com/uPhyca/gradle-android-aspectj-plugin

Categories

Resources