Below is the build.gradle file:
plugins({
id('application')
id 'java'
id('com.github.johnrengelman.shadow').version('4.0.1')
})
allprojects(
{
apply(plugin: 'application')
apply(plugin: 'java')
apply(plugin: 'com.github.johnrengelman.shadow')
repositories({
mavenCentral()
})
ext({
vertxVersion = '3.7.0'
commitTimestamp = {
return "git log -1 --pretty=format:%cd --date=format:%Y%m%d%H%M%S".execute().text.trim()
}
commitId = {
return "git rev-parse --short HEAD".execute().text.trim()
}
buildId = {
if (System.getenv("BUILD_ID") != null) return ".${System.getenv("BUILD_ID")}"
else return ""
}
})
group = 'com.pluralsight.docker-production-aws'
version = System.getenv("APP_VERSION") ?: "${commitTimestamp()}.${commitId()}${buildId()}"
sourceCompatibility = '1.8'
mainClassName = 'io.vertx.core.Launcher'
dependencies({
compile("io.vertx:vertx-core:$vertxVersion")
compile("io.vertx:vertx-hazelcast:$vertxVersion")
compile("io.vertx:vertx-service-discovery:$vertxVersion")
compile("io.vertx:vertx-dropwizard-metrics:$vertxVersion")
compile("com.typesafe:config:1.3.0")
compile("com.hazelcast:hazelcast-cloud:3.6.5")
testCompile("io.vertx:vertx-unit:$vertxVersion")
testCompile("junit:junit:4.12")
testCompile("org.assertj:assertj-core:3.5.2")
testCompile("com.jayway.awaitility:awaitility:1.7.0")
})
task(copyDeps(type: Copy), {
from (configurations.runtime + configurations.testRuntime).exclude('*')
into('/tmp')
}
)
test(
{
testLogging(
{
events("passed", "skipped", "failed")
}
)
reports(
{
junitXml.enabled = true
junitXml.destination = file("${rootProject.projectDir}/build/test-results/junit")
html.enabled = false
}
)
}
)
}
)
task(testReport(type: TestReport), {
destinationDir = file("${rootProject.projectDir}/build/test-results/html")
reportOn(subprojects*.test)
}
)
test(
{
dependsOn(testReport)
}
)
configure(
(subprojects - project(':microtrader-common')),
{
shadowJar(
{
destinationDir = file("${rootProject.projectDir}/build/jars")
classifier = 'fat'
mergeServiceFiles(
{
include('META-INF/services/io.vertx.core.spi.VerticleFactory')
}
)
}
)
}
)
task(
wrapper(type: Wrapper),
{
gradleVersion = '4.10.2'
}
)
that gives below error on /gradlew clean test shadowJar:
> Could not find method copyDeps() for arguments
for problem code snippet:
task(copyDeps(type: Copy), {
from (configurations.runtime + configurations.testRuntime).exclude('*')
into('/tmp')
}
task(testReport(type: TestReport), {
destinationDir = file("${rootProject.projectDir}/build/test-results/html")
reportOn(subprojects*.test)
}
)
task(
wrapper(type: Wrapper),
{
gradleVersion = '4.10.2'
}
)
./gradlew Command works with below code snippet syntax without paranthesis:
task copyDeps(type: Copy) {
from (configurations.runtime + configurations.testRuntime) exclude '*'
into '/tmp'
}
task testReport(type: TestReport) {
destinationDir = file("${rootProject.projectDir}/build/test-results/html")
reportOn subprojects*.test
}
task wrapper(type: Wrapper) {
gradleVersion = '4.10.2'
}
Does build.gradle have syntax issue? using paranthesis...We prefer using paranthesis
https://docs.gradle.org/current/userguide/more_about_tasks.html shows examples of how to define custom tasks.
Here is how you can define your tasks the verbose way.
tasks.create('copyDeps', Copy, {
from(file('srcDir'))
into(buildDir)
})
The tasks are created using the TaskContainer which offers several overloads for the create method. Here is a subset:
create(String name)
create(String name, Closure configureClosure)
create(String name, Class<T> type, Action<? super T> configuration) <-- this is the one used above
create(Map<String,?> options, Closure configureClosure)
Related
I am trying to build my Java 11 project to have either an executable jar (FatJar, SuperJar, whatever its called) or an EXE or any form of runnable version even a batch file (Using Application). Everything I try I either get JavaFX is missing or my dependencies included the packages arent visible and it error's out.
Here is my build.gradle
plugins {
id 'application'
id 'java'
id 'maven-publish'
id 'org.openjfx.javafxplugin' version '0.0.8'
id 'edu.sc.seis.launch4j' version '2.4.6'
id 'org.beryx.jlink' version '2.12.0'
}
application {
mainClassName = 'sassa.sassa.Main'
}
repositories {
mavenLocal()
maven {
url = uri('https://jitpack.io')
}
maven {
url = uri('https://repo.maven.apache.org/maven2')
}
}
javafx {
version = "11.0.2"
modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.graphics' ]
}
jlink {
launcher {
name = 'sassa'
}
}
dependencies {
implementation 'com.github.toolbox4minecraft:amidst:v4.4-beta1'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
}
jar {
manifest {
attributes("Manifest-Version": "1.0",
"Main-Class": "sassa.main.Main");
}
}
compileJava {
doFirst {
println "CLASSPATH IS $classpath.asPath"
options.compilerArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.graphics',
'--add-modules', 'javafx.controls',
'--add-modules', 'javafx.fxml'
]
classpath = files()
}
}
task fatJar(type: Jar) {
manifest.from jar.manifest
classifier = 'all'
from {
configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} {
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
with jar
}
launch4j {
mainClassName = 'sassa.main.Main'
icon = "${projectDir}/src/main/resources/sassa/sassa.ico"
jreMinVersion = '11'
jreMaxVersion = '14'
jdkPreference = 'preferJre'
initialHeapSize = 128
maxHeapSize = 512
stayAlive = false
bundledJre64Bit = true
dontWrapJar = true
bundledJrePath = 'jre'
}
group = 'sassa'
version = '0.5.0'
sourceCompatibility = '11'
publishing {
publications {
maven(MavenPublication) {
from(components.java)
}
}
}
Also for the layout of the project it is on github (I was using maven before but figured Gradle might work better. (The maven code is still on github) https://github.com/Zodsmar/SeedSearcherStandaloneTool/tree/development
Literally I have tried everything and I just can't seem to get a buildable version to distribute...
Also I have read up about module.info files I do not have any I want to have a simple build.gradle that just includes everything I need to build an executable.
To anyone whoever comes across this and wants to know how I fixed it. I created a Gradle build task and then was able to build Jars, EXEs, Tar, and Zip this is the gradle:
plugins {
id 'application'
id 'java'
id 'maven-publish'
id 'org.openjfx.javafxplugin' version '0.0.8'
id 'edu.sc.seis.launch4j' version '2.4.6'
}
dependencies {
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
implementation ('com.github.KaptainWutax:BiomeUtils:master-SNAPSHOT') {
transitive = false;
changing = true;
}
implementation ('com.github.KaptainWutax:FeatureUtils:master-SNAPSHOT')
{
transitive = false;
changing = true;
}
implementation ('com.github.KaptainWutax:SeedUtils:master-SNAPSHOT')
{
transitive = false;
changing = true;
}
}
group = 'sassa'
version = 'v0.6.0'
sourceCompatibility = '1.8'
String stringVersion = version
javafx {
version = "11.0.2"
modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.graphics' ]
}
application {
mainClassName = 'sassa.main.Main'
}
jar {
manifest {
attributes 'Main-Class': 'sassa.main.Main'
}
from {
configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
launch4j {
mainClassName = 'sassa.main.Main'
outfile = group + "-" + stringVersion + ".exe"
icon = "${projectDir}/src/main/resources/sassa/sassa.ico"
}
repositories {
mavenLocal()
maven {
url = uri('https://jitpack.io')
}
maven {
url = uri('https://repo.maven.apache.org/maven2')
}
}
task buildAll(type: GradleBuild) {
tasks = ['jar', 'createExe', 'assemble']
}
publishing {
publications {
maven(MavenPublication) {
from(components.java)
}
}
}
I'm building a fat jar with the code below. However, I have multiple property files with the same name in different jars, which are collected into the fat jar.
I guess the solution is to concatenate/merge the files with the same name into one file, but how do I do it? I found this question How do I concatenate multiple files in Gradle?.
How can I access and merge the property files (let's name them myproperties.properties) in the it objects?
task fatJar(type: Jar) {
def mainClass = "myclass"
def jarName = "myjarname"
zip64=true
manifest {
attributes(
'Main-Class': mainClass,
'Class-Path': configurations.compile.collect { it.getName() }.join(' ')
)
}
baseName = project.name + '-' + jarName + '-all'
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
{
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}
with jar
}
Solution:
I marked the given answer as the solution although I haven't tried it. Instead we solved the problem by creating multiple jars and adding those to the classpath.
Possibly you could write a custom MergeCopy task. Eg
public interface FileMerger implements Serializable {
public void merge(String path, List<File> files, OutputStream out) throws IOException;
}
public class MergeCopy extends DefaultTask {
private File outputDir;
private List<FileTree> fileTrees = []
#TaskInput
FileMerger merger
#OutputDirectory
File getOutputDir() {
return outputDir
}
#InputFiles
List<FileTree> getFileTrees() {
return fileTrees
}
void from(FileTree fileTree) {
fileTrees.add(fileTree)
}
void into(Object into) {
outputDir = project.file(into)
}
#TaskAction
void copyAndMerge() {
Map<String, List<File>> fileMap = [:]
FileTree allTree = project.files().asFileTree
fileTrees.each { FileTree fileTree ->
allTree = allTree.plus(fileTree)
fileTree.visit { FileVisitDetails fvd ->
String path = fvd.path.path
List<File> matches = fileMap[path] ?: []
matches << fvd.file
fileMap[path] = matches
}
}
Set<String> dupPaths = [] as Set
Set<String> nonDupPaths = [] as Set
fileMap.each { String path, List<File> matches ->
if (matches.size() > 1) {
dupPaths << path
} else {
nonDupPaths << path
}
}
FileTree nonDups = allTree.matching {
exclude dupPaths
}
project.copy {
from nonDups
into outputDir
}
for (String dupPath : dupPaths) {
List<File> matches = fileMap[dupPath]
File outFile = new File(outputDir, dupPath)
outFile.parentFile.mkdirs()
try (OutputStream out = new FileOutputStream(outFile)) {
merger.merge(dupPath, matches, out)
out.flush()
}
}
}
}
You could then do
task mergeCopy(type: MergeCopy) {
configurations.compile.files.each {
from it.directory ? fileTree(it) : zipTree(it)
}
into "$buildDir/mergeCopy"
merger = { String path, List<File> files, OutputStream out ->
// TODO: implement
}
}
task fatJar(type: Jar) {
dependsOn mergeCopy
from mergeCopy.outputDir
...
}
I'm trying to clean build project with Spring boot plugin and getting the following message:
Execution failed for task ':lecture05:findMainClass'.
Unable to find a single main class from the following candidates [ru.atom.boot.mm.MatchMakerApp, ru.atom.boot.hw.HelloSpringBoot]
I can't find any information for this case here. I've found a couple of questions like this, but this is for maven. How to config my project correctly?
I was trying to add
bootRepackage {
mainClass = 'ru.atom.boot.mm.MatchMakerApp'
}
to build.gradle
My root project:
plugins {
id 'org.springframework.boot' version '1.5.8.RELEASE'
id 'com.github.kt3k.coveralls' version '2.6.3'
}
bootRepackage {
mainClass = 'ru.atom.boot.mm.MatchMakerApp'
}
ext {
jdkVersion = 1.9
jettyVersion = "9.4.7.v20170914"
junitVersion = "4.12"
jacksonVersion = "2.9.1"
log4jVersion = "2.7"
jetbrainsAnnotationVersion = "15.0"
okhttpVersion = "3.6.0"
jerseyVersion = "2.26"
gsonjVersion = "2.7"
postgresVersion = "9.4-1200-jdbc41"
jetbrainsAnnotationVersion = "15.0"
hibernateVersion = "5.2.3.Final"
websocketVersion = "9.4.3.v20170317"
jolVersion = "0.8"
}
allprojects {
group = "technoatom"
version = "1.0-SNAPSHOT"
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'checkstyle'
apply plugin: 'jacoco'
repositories {
mavenCentral()
}
sourceCompatibility = jdkVersion
targetCompatibility = jdkVersion
}
subprojects {
checkstyle {
ignoreFailures = false
toolVersion = '7.5'
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
}
tasks.withType(Checkstyle) {
reports {
xml.enabled false
html.destination
"$rootProject.buildDir/report/${project.name}.html"
html.stylesheet
resources.text.fromFile(rootProject.file('config/checkstyle/checkstyle-custom.xsl'))
}
}
}
ext.libraries = [
spring_boot : [
"org.springframework.boot:spring-boot-starter-web",
"org.springframework.boot:spring-boot-starter-actuator"
],
spring_boot_test : "org.springframework.boot:spring-boot-starter-test",
jetty_server : "org.eclipse.jetty:jetty-server:$jettyVersion",
jetty_servlet: "org.eclipse.jetty:jetty-servlet:$jettyVersion",
junit: "junit:junit:$junitVersion",
log4j: [
"org.apache.logging.log4j:log4j-api:$log4jVersion",
"org.apache.logging.log4j:log4j-core:$log4jVersion"
],
jetbrainsAnnotations: "org.jetbrains:annotations:$jetbrainsAnnotationVersion",
okhttp: "com.squareup.okhttp3:okhttp:$okhttpVersion",
jersey_server: "org.glassfish.boot.core:boot-server:$jerseyVersion",
jersey_hk2: "org.glassfish.boot.inject:boot-hk2:$jerseyVersion",
jersey_containers: "org.glassfish.boot.containers:boot-container-servlet:$jerseyVersion",
jersey_test:
"org.glassfish.boot.test-framework.providers:boot-test-framework-provider-grizzly2:$jerseyVersion",
gson: "com.google.code.gson:gson:$gsonjVersion",
postgres: "org.postgresql:postgresql:$postgresVersion",
hibernate: "org.hibernate:hibernate-core:$hibernateVersion",
websocketclient: "org.eclipse.jetty.websocket:websocket-client:$websocketVersion",
websocketserver: "org.eclipse.jetty.websocket:websocket-server:$websocketVersion",
websocketapi: "org.eclipse.jetty.websocket:websocket-api:$websocketVersion",
jackson: "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion",
jol: "org.openjdk.jol:jol-core:$jolVersion",
jol_samples: "org.openjdk.jol:jol-samples:$jolVersion"
]
jacocoTestReport {
additionalSourceDirs =
files(subprojects.sourceSets.main.allSource.srcDirs)
sourceDirectories =
files(subprojects.sourceSets.main.allSource.srcDirs)
classDirectories = files(subprojects.sourceSets.main.output)
executionData = files(subprojects.jacocoTestReport.executionData)
onlyIf = {
true
}
reports {
xml.enabled = true
html.enabled = true
}
doFirst {
executionData = files(executionData.findAll {
it.exists()
})
}
}
coveralls {
sourceDirs =
files(subprojects.sourceSets.main.allSource.srcDirs).files.absolutePath
}
Subproject, I'm trying to build, that has two Main classes:
dependencies {
compile rootProject.libraries.spring_boot
compile rootProject.libraries.log4j
testCompile rootProject.libraries.junit
testCompile rootProject.libraries.spring_boot_test
}
sourceSets {
main {
java {
srcDirs = ['src/main/java']
}
}
test {
java {
srcDirs = ['src/test/java']
}
}
}
Try to replace it with:
springBoot {
mainClass = 'ru.atom.boot.mm.MatchMakerApp'
}
As jprism mentioned you can read more in Spring Boot plugin docs
One of my plugins uses the files created by the gradle build of another project.
However gradle evaluates the plugin task before building. Is there a way to make the plugin tasks be created after the build is completed?
EDIT:
Here is the build.gradle
apply plugin: 'confluence-export'
sourceSets {
tools
}
compileToolsJava {
source += sourceSets.main.java
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
toolsCompile files("${System.getProperty('java.home')}/../lib/tools.jar")
}
task generateTagDoc(type: JavaExec) {
classpath = sourceSets.tools.runtimeClasspath
main = 'TagsDocumentation'
outputs.upToDateWhen { false }
}
task generateTypeDoc(type: Javadoc) {
classpath = sourceSets.tools.runtimeClasspath
source = sourceSets.main.allJava
options.docletpath = compileToolsJava.outputs.files.asList()
options.doclet = "ExtractCommentsDoclet"
options.addStringOption("Tags.java")
outputs.upToDateWhen { false }
}
confluence {
spaceKey = *****
exportAll = true
title = *******
exportUser = "******
exportPassword = ******
libraryName = ******
host = ********
}
asciidoctor {
resources {
from(sourceDir) {
include 'img/**'
}
}
}
asciidoctor.dependsOn(generateTagDoc)
generateTagDoc.dependsOn(generateTypeDoc)
generateTypeDoc.dependsOn(compileToolsJava)
So here I want my build to run which will create a folder asciidoc/html5 in the build folder with all my created html pages from my asciidoc files. My plugin goes through each file and creates a task for it and then uploads it to a website. The problem is the plugin task is evaluated before the build so the folder asciidoc/html5 hasn't been created yet. If i add a check to see if the folder has been created it will indeed remove my error however the task will still be empty. This is why i would like to know if there is a way for the plugin tasks to be created after the build is done so that the folder is created.
EDIT 2:
Here is the plugin creation:
class ConfluenceExportPlugin extends ConfluencePluginBase implements Plugin<Project> {
#Override
void apply(Project project) {
def confluenceExtension = project.extensions.create('confluence', ConfluenceExtension)
project.afterEvaluate {
if (confluenceExtension.exportAll) {
def list = []
def dir = new File("${project.buildDir}/asciidoc/html5")
if(dir.exists() && dir.isDirectory())
dir.eachFileRecurse(FileType.FILES) {
if(it.name.endsWith('.html')) {
list.add(it)
}
}
Task mainTask = project.task('confluenceExport')
mainTask.dependsOn("build")
list.each { file ->
def curName = file.name.take(file.name.lastIndexOf('.'))
ConfluenceExportTask subTask = createTask(project, "confluenceExport${curName}", confluenceExtension, file.path, curName)
mainTask.dependsOn(subTask)
}
}
else {
ConfluenceExportTask task = createTask(project, "confluenceExport", confluenceExtension, getManFile(confluenceExtension, project), confluenceExtension.title)
}
}
}
ConfluenceExportTask createTask(Project project, String taskName, def confluenceExtension, manFile, String pageTitle ){
ConfluenceExportTask task = project.task(type: ConfluenceExportTask, taskName)
task.conventionMapping.map "user", { confluenceExtension.user }
task.conventionMapping.map "password", { confluenceExtension.password }
task.conventionMapping.map "spaceKey", { confluenceExtension.spaceKey }
task.conventionMapping.map "manFile", { manFile }
task.conventionMapping.map "pageTitle", { pageTitle }
task
}
String getManFile(ConfluenceExtension configuration, Project project) {
configuration.exportSourceFilePath ?: "${project.buildDir}/asciidoc/html5/${configuration.libraryName}.html"
}
}
I was able to successfully run my project in Eclipse. But when i am trying to upgrade my project to Android studio it stopped working for me. I have tried every thing but it is not working. Below is my build.gradle file code.
apply plugin: 'android'
buildscript {
repositories {
mavenCentral()
}
// Switch the Android Gradle plugin version requirement depending on the
// installed version of Gradle. This dependency is documented at
// http://tools.android.com/tech-docs/new-build-system/version-compatibility
// and https://issues.apache.org/jira/browse/CB-8143
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
}
}
// Allow plugins to declare Maven dependencies via build-extras.gradle.
repositories {
mavenCentral()
}
task wrapper(type: Wrapper) {
gradleVersion = '2.2.1'
}
// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
apply from: 'CordovaLib/cordova.gradle'
// The value for android.compileSdkVersion.
if (!project.hasProperty('cdvCompileSdkVersion')) {
cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
// The value for android.buildToolsVersion.
if (!project.hasProperty('cdvBuildToolsVersion')) {
cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
// Sets the versionCode to the given value.
if (!project.hasProperty('cdvVersionCode')) {
cdvVersionCode = null
}
// Sets the minSdkVersion to the given value.
if (!project.hasProperty('cdvMinSdkVersion')) {
cdvMinSdkVersion = null
}
// Whether to build architecture-specific APKs.
if (!project.hasProperty('cdvBuildMultipleApks')) {
cdvBuildMultipleApks = false
}
// .properties files to use for release signing.
if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
cdvReleaseSigningPropertiesFile = null
}
// .properties files to use for debug signing.
if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
cdvDebugSigningPropertiesFile = null
}
// Set by build.js script.
if (!project.hasProperty('cdvBuildArch')) {
cdvBuildArch = null
}
}
def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
apply from: 'build-extras.gradle'
}
def computeBuildTargetName(debugBuild) {
def ret = 'assemble'
if (cdvBuildMultipleApks && cdvBuildArch) {
def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
}
return ret + (debugBuild ? 'Debug' : 'Release')
}
// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
return computeBuildTargetName(true)
}
task cdvBuildRelease
cdvBuildRelease.dependsOn {
return computeBuildTargetName(false)
}
task cdvPrintProps << {
println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
println('cdvVersionCode=' + cdvVersionCode)
println('cdvMinSdkVersion=' + cdvMinSdkVersion)
println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
println('cdvBuildArch=' + cdvBuildArch)
println('computedVersionCode=' + android.defaultConfig.versionCode)
if (android.productFlavors.has('armv7')) {
println('computedArmv7VersionCode=' + android.productFlavors.armv7.versionCode)
}
if (android.productFlavors.has('x86')) {
println('computedx86VersionCode=' + android.productFlavors.x86.versionCode)
}
}
// PLUGIN GRADLE EXTENSIONS START
// PLUGIN GRADLE EXTENSIONS END
android {
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
def versionCodeOverride = cdvVersionCode ? Integer.parseInt(cdvVersionCode) : null
def minSdkVersionOverride = cdvMinSdkVersion ? Integer.parseInt(cdvMinSdkVersion) : null
defaultConfig {
versionCode versionCodeOverride ?: Integer.parseInt("" + privateHelpers.extractIntFromManifest("versionCode") + "0")
if (minSdkVersionOverride != null) {
minSdkVersion minSdkVersionOverride
}
}
compileSdkVersion cdvCompileSdkVersion
buildToolsVersion cdvBuildToolsVersion
if (Boolean.valueOf(cdvBuildMultipleApks)) {
productFlavors {
armv7 {
versionCode versionCodeOverride ?: defaultConfig.versionCode + 2
ndk {
abiFilters "armeabi-v7a", ""
}
}
x86 {
versionCode versionCodeOverride ?: defaultConfig.versionCode + 4
ndk {
abiFilters "x86", ""
}
}
all {
ndk {
abiFilters "all", ""
}
}
}
} else if (!versionCodeOverride) {
def minSdkVersion = minSdkVersionOverride ?: privateHelpers.extractIntFromManifest("minSdkVersion")
// Vary versionCode by the two most common API levels:
// 14 is ICS, which is the lowest API level for many apps.
// 20 is Lollipop, which is the lowest API level for the updatable system webview.
if (minSdkVersion >= 20) {
defaultConfig.versionCode += 9
} else if (minSdkVersion >= 14) {
defaultConfig.versionCode += 8
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
if (cdvReleaseSigningPropertiesFile) {
signingConfigs {
release {
// These must be set or Gradle will complain (even if they are overridden).
keyAlias = ""
keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.
storeFile = null
storePassword = "__unset"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
}
if (cdvDebugSigningPropertiesFile) {
addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
}
}
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
// SUB-PROJECT DEPENDENCIES START
// SUB-PROJECT DEPENDENCIES END
}
def promptForReleaseKeyPassword() {
if (!cdvReleaseSigningPropertiesFile) {
return;
}
if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
}
if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
}
}
gradle.taskGraph.whenReady { taskGraph ->
taskGraph.getAllTasks().each() { task ->
if (task.name == 'validateReleaseSigning') {
promptForReleaseKeyPassword()
}
}
}
def addSigningProps(propsFilePath, signingConfig) {
def propsFile = file(propsFilePath)
def props = new Properties()
propsFile.withReader { reader ->
props.load(reader)
}
def storeFile = new File(privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
if (!storeFile.isAbsolute()) {
storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
}
if (!storeFile.exists()) {
throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
}
signingConfig.keyAlias = privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
signingConfig.keyPassword = props.get('keyPassword', signingConfig.keyPassword)
signingConfig.storeFile = storeFile
signingConfig.storePassword = props.get('storePassword', signingConfig.storePassword)
def storeType = props.get('storeType')
if (!storeType) {
def filename = storeFile.getName().toLowerCase();
if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
storeType = 'pkcs12'
}
}
if (storeType) {
signingConfig.storeType = storeType
}
}
// This can be defined within build-extras.gradle as:
// ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
Once i run the code and try to open my application custom keyboard get following exception.
E/BinaryDictionary: Could not load native library jni_latinime
12-06 15:22:01.269 8412-8412/com.KGP.inputmethod.latin E/art: No implementation found for int com.android.inputmethod.latin.BinaryDictionary.openNative(java.nio.ByteBuffer, int, int) (tried Java_com_android_inputmethod_latin_BinaryDictionary_openNative and Java_com_android_inputmethod_latin_BinaryDictionary_openNative__Ljava_nio_ByteBuffer_2II)
12-06 15:22:01.270 8412-8412/com.KGP.inputmethod.latin D/AndroidRuntime: Shutting down VM
12-06 15:22:01.271 8412-8412/com.KGP.inputmethod.latin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.KGP.inputmethod.latin, PID: 8412
java.lang.UnsatisfiedLinkError: No implementation found for int com.android.inputmethod.latin.BinaryDictionary.openNative(java.nio.ByteBuffer, int, int) (tried Java_com_android_inputmethod_latin_BinaryDictionary_openNative and Java_com_android_inputmethod_latin_BinaryDictionary_openNative__Ljava_nio_ByteBuffer_2II)
at com.android.inputmethod.latin.BinaryDictionary.openNative(Native Method)
at com.android.inputmethod.latin.BinaryDictionary.loadDictionary(BinaryDictionary.java:151)
at com.android.inputmethod.latin.BinaryDictionary.<init>(BinaryDictionary.java:82)
at com.android.inputmethod.latin.Suggest.<init>(Suggest.java:114)
at com.android.inputmethod.latin.LatinIME.initSuggest(LatinIME.java:494)
at com.android.inputmethod.latin.LatinIME.onCreate(LatinIME.java:399)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2945)
at android.app.ActivityThread.access$1900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1467)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Below is my project folder structure :-
My Class code where i am uploading lib :-
static {
try {
System.loadLibrary("jni_latinime_moo");
} catch (UnsatisfiedLinkError ule) {
Log.e("BinaryDictionary",
"Could not load native library jni_latinime");
}
}
I am not sure what i am doing wrong here. I am very thankful who ever can help me out.
I have resolved my issue using this link :-
stackoverflow.com/questions/21096819/jni-and-gradle-in-android-studio