Java Import build.gradle file for minecraft mod - java

I have been following this tutorial - https://mcforge.readthedocs.io/en/latest/gettingstarted/
- and I am stuck on this section - Launch IDEA and choose to open/import the build.gradle file, using the default gradle wrapper choice. While you wait for this process to finish, you can open the gradle panel, which will get filled with the gradle tasks once importing is completed.
How do I import the build.gradle file? what is the build.gradle file? what does it do? I am new to coding, any help is appreciated. thx

Launch IDEA and select "File" → "New" → "Project from Existing Sources"
Select build.gradle file from the unpacked archive from the site you've provided
Check wrapper settings on the next screen. Leave the defaults.
Wait till IDEA builds the projects and makes indexes.
Happy hacking!
build.gradle is basically a build configuration file. It describes the way a piece of software is made. Like: where is the source code, what are the project's dependencies, where to get and how to link them, how to test and so on.
Speaking about particular build.gradle from forge-mdk:
buildscript {
repositories {
jcenter()
maven { url = "https://files.minecraftforge.net/maven" }
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
This part applies net.minecraftforge.gradle.forge plugin that, I guess, is used to build Minecraft mods. As this is a third-party plugin buildscript block adds a repository (https://files.minecraftforge.net/maven) where it can be downloaded.
version = "1.0"
group = "com.yourname.modid" // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = "modid"
This part describes the result ("artifact") of the projects. It has version 1.0, name modid and will be published (if published) under com.yourname.modid group. This is a Maven related vocabulary. I guess, you'll need to replace this values with your own.
sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
}
Here you state that the projects is built with Java 8
minecraft {
version = "1.12.2-14.23.5.2775"
runDir = "run"
mappings = "snapshot_20171003"
}
Here you configure net.minecraftforge.gradle.forge plugin that you've added previously. Basically, any plugin can expose it's own configuration block and you'll need to read the docs to know what do the values mean.
dependencies {
…
}
The project has no dependencies yet, thus empty dependencies block
processResources {
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else except the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
Here you configure built-int processResources task that… processes resources. As you see, things are self-descriptive in Gradle. Tasks are Java classes that has documentation. For example, here are the docs for ProcessResources. One more link for DSL reference
Hope this answer will get you some info to start with!

Related

Gradle: Call Task from Imported Plugin in My Own Tasks

I'm used to Maven but currently I'm using Gradle and I'm not really sure how to call tasks defined by other plugins. (Edit: I'm able to call these tasks in the CLI, but I'd like to also invoke them in my own, custom-defined tasks.)
But I'm importing this plugin to format (and enforce format) of my Java project; the tasks I'm most interested in calling are goJF and verGJF.
I've tried a few ways to either call included tasks and I've done even more Googling. I can share some of the (probably embarrassing) ways I've tried to call other tasks if it's helpful, but figured that might be unnecessary information at this point.
Here is my build.gradle:
plugins {
id 'java'
// https://github.com/sherter/google-java-format-gradle-plugin
id 'com.github.sherter.google-java-format' version '0.9'
}
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:30.0-jre")
testImplementation(platform('org.junit:junit-bom:5.7.0'))
testImplementation('org.junit.jupiter:junit-jupiter:5.7.0')
}
// Alias for goJF:
task fmt {
goJF
}
// Alias for verGJF:
task vfmt {
verGJF
}
test {
useJUnitPlatform()
}
Working example here.
From the documentation, we note that there are examples of configuring the plugin tasks. So aliasing is a simplification of that approach. Consider:
plugins {
id 'java'
// https://github.com/sherter/google-java-format-gradle-plugin
id 'com.github.sherter.google-java-format' version '0.9'
}
import com.github.sherter.googlejavaformatgradleplugin.GoogleJavaFormat
import com.github.sherter.googlejavaformatgradleplugin.VerifyGoogleJavaFormat
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:30.0-jre")
testImplementation(platform('org.junit:junit-bom:5.7.0'))
testImplementation('org.junit.jupiter:junit-jupiter:5.7.0')
}
task fmt(type: GoogleJavaFormat) {
}
task vfmt(type: VerifyGoogleJavaFormat) {
}
test {
useJUnitPlatform()
}
Here fmt is a new task of type GoogleJavaFormat; vfmt is of type VerifyGoogleJavaFormat. These instances can specify their own configuration (and do other things with doFirst, doLast, etc). But as-is, they act as aliases.
A few distinctions to begin with. The built in tasks defined by the plugin are called googleJavaFormat and verifyGoogleJavaFormat.
These tasks are immediately available to you once you have included the plugin which it seems you have done correctly from what I can see.
On the gradle command line, gradle implements a abbreviation functionality where you can call things with shorthand like:
~> gradle gooJF
which is shorthand for:
~> gradle googleJavaFormat
but this only works on the command line and only as long as your shorthand uniquely identifies a task name.
So when you work with tasks in the build.gradle file you will need to use the full name.
In gradle you create a new task via:
task SomeTaskName(type: SomeClassImplementingTheTask) {
// some configuration of the task
}
In your case you would want to do one of two things:
configure the two existing tasks added by the plugin so that they do what you want or if the tasks already do what they should, you might not need to configure them and can just run them as is.
create your own tasks with your own names but using the implementing classes (i.e. replacing SomeClassNameImplementingTheTask above with GoogleJavaFormat or VerifyGoogleJavaFormat) defined by the plugin.
The simplest of the two is to configure the already existing tasks. This can be done as follows:
googleJavaFormat {
source = sourceSets*.allJava
source 'src/special_dir'
include '**/*.java'
exclude '**/*Template.java'
exclude 'src/test/template_*'
}
The googleJavaFormat used here is actually a "plugin extension" which is exposed by the plugin. Plugin extensions are explicitly there for you to be able to alter the behavior of the plugin through configuration.
Note that the configurations options I defined are just examples, there are probably more things you can set here. The above would modify the two existing tasks with your custom settings and you could then call them from the command line using:
~> gradle googleJavaFormat
and
~> gradle verifyGoogleJavaFormat
Again, perhaps you don't even need to configure things and in that case you should just be able to call the tasks as in the above example.

Gradle's Maven Publish plugin not publishing POM or proper version to Maven Local

I am trying to get the Gradle Maven Publish Plugin to publish a snapshot version of my Java library to my local Maven repo such that:
The version of the jar is 1.0.0.SNAPSHOT-<timestamp>, where <timestamp> is the current system time in millis (similar to something like System.currentTimeInMillis()); and
I log to STDOUT/console the full name of the jar being published, including the version above; and
A properly-formatted pom.xml is published to Maven local alongside the jar, so that any other Gradle/Maven projects can "pull it down" locally and fetch its transitive dependencies properly
My best attempt so far:
plugins {
id 'java-library'
id 'maven-publish'
}
dependencies {
compile(
'org.hibernate:hibernate-core:5.0.12.Final'
,'com.fasterxml.jackson.core:jackson-core:2.8.10'
,'com.fasterxml.jackson.core:jackson-databind:2.8.10'
,'com.fasterxml.jackson.core:jackson-annotations:2.8.0'
)
testCompile(
'junit:junit:4.12'
)
}
repositories {
jcenter()
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
group 'com.me'
jar {
baseName = 'my-lib'
version = '1.0.0-SNAPSHOT'
}
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
}
However, with this setup, when I run ./gradlew publishToMavenLocal:
I do see the jar being deployed to ~/.m2/repository/com/me/my-lib/ but without a pom.xml and no 1.0.0.SNAPSHOT version appended to it
I don't even know how/where I would append the timestamp onto the version
I don't even know how/where I would do a println(...) to report the full name of the jar being published
Any ideas?
Regarding #3, To install your artifact to a local repository you do not need the maven-publish plugin, rather the maven plugin
See The Maven plugin documentation, specifically the Tasks section and the Installing to the local repository section with it, you can run gradle clean build install
It works for me with a build.gradle file as simple as this
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'maven'
Note, if you need to publish something other then the default generated jar then you need to change the archives configuration
Regarding #1 appending the timestamp, move the version line outside the jar clause and change it from
version = '1.0.0-SNAPSHOT'
to
version = "1.0-SNAPSHOT-${System.currentTimeMillis()}"
This is using Groovy GString (AKA string interpolation - note the change from single quotes to double quotes) to append the current time in millis to the version
Last but not least, regarding #2 printing the jar full name append the following to the build.gradle file
install.doLast {
println jar.archiveName
}
Essentially we're appending to the install task (the one executed in the top of my answer) a println of the jar configuration's archiveName (see here if you want something else)
So all in all my build.gradle file looks like this:
group 'com.boazj'
version "1.0-SNAPSHOT-${System.currentTimeMillis()}"
apply plugin: 'java'
apply plugin: 'maven'
install.doLast {
println jar.archiveName
}

How to make the gradle ShadowJar task also create sources and javadoc of its children?

I have a gradle project with 8 child projects and a configured shadowjar task to create an "all" jar. The toplevel project is setup to have dependencies to all its children, this tells shadowjar what to include:
project(':') {
dependencies {
compile project(':jfxtras-agenda')
compile project(':jfxtras-common')
compile project(':jfxtras-controls')
compile project(':jfxtras-icalendarfx')
compile project(':jfxtras-icalendaragenda')
compile project(':jfxtras-menu')
compile project(':jfxtras-gauge-linear')
compile project(':jfxtras-font-roboto')
}
}
shadowJar {
classifier = null // do not append "-all", so the generated shadow jar replaces the existing jfxtras-all.jar (instead of generating jfxtras-all-all.jar)
}
This works fine, but maven central is refusing the all jar, because it does not have an associated sources and javadocs jar.
How do I tell gradle to also generate the sources and javadoc? ShadowJar's documentation says it should do this by default.
The shadow plugin doesn't seem to have a feature of building a fat sources/javadocs jars.
Below, I provide a few short tasks (javadocJar and sourcesJar) that will build fat javadoc and source jars. They are linked to be always executed after shadowJar. But it has no dependency on the shadow jar plugin.
subprojects {
apply plugin: 'java'
}
// Must be BELOW subprojects{}
task alljavadoc(type: Javadoc) {
source subprojects.collect { it.sourceSets.main.allJava }
classpath = files(subprojects.collect { it.sourceSets.main.compileClasspath })
destinationDir = file("${buildDir}/docs/javadoc")
}
task javadocJar(type: Jar, dependsOn: alljavadoc) {
classifier = 'javadoc'
from alljavadoc.destinationDir
}
task sourcesJar(type: Jar) {
classifier = 'sources'
from subprojects.collect { it.sourceSets.main.allSource }
}
shadowJar.finalizedBy javadocJar
shadowJar.finalizedBy sourcesJar
Note, the subprojects section is required, even if you already apply the java plugin inside your subprojects.
Also note, it doesn't include javadocs of the third party libraries your subprojects might depend on. But usually you wouldn't want to do it anyway, probably.
This is an old thread, but I'm posting my solution, as it's a lot easier than the above, and I've confirmed it works:
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.0'
id 'signing'
id 'maven-publish'
}
// If using Spring Boot, this is needed
jar.enabled = true
jar.dependsOn shadowJar
java {
withJavadocJar()
withSourcesJar()
}
// Remove the -all extension from the "fat" Jar, or it can't be used
// when published to Maven Central.
shadowJar {
archiveClassifier.set('')
}
// The contents of this section are described here:
// https://docs.gradle.org/current/userguide/publishing_maven.html
publishing {
publications {
jwtopaLibrary(MavenPublication) {
artifactId = 'jwt-opa'
artifacts = [ shadowJar, javadocJar, sourcesJar ]
pom {
// etc. ...
}
// Signs the `publication` generated above with the name `jwtopaLibrary`
// Signing plugin, see: https://docs.gradle.org/current/userguide/signing_plugin.html#signing_plugin
signing {
sign publishing.publications.jwtopaLibrary
}
It's not made clear anywhere, and the information needs to be collected in several places, but for the signing plugin to work, you need the short form hex key ID:
# gradle.properties
# The `signing` plugin documentation is less than helpful;
# however, this is the magic incantation to find the `keyId`:
#
# gpg --list-signatures --keyid-format 0xshort
#
# The key also needs to be distributed to public GPG servers:
#
# gpg --keyserver keyserver.ubuntu.com --send-keys 123...fed
#
# In all cases, we need to use the values from the `pub` key.
signing.keyId=0x1234abcde
Then, it's just a matter of running ./gradlew publish and magic happens (well, not really, you still have to go to Sonatype repository, do the "close & release dance", but you know, whatever).

Intellij Idea 13 UI Designer and automatic Gradle building

I've used the Intellij UI Designer to create forms for a project. Everything works fine when I'm building with idea as it handles compiling the forms for me, but as we recently switched to using Gradle for building it hasn't been possible to produce an executable jar file yet.
My google-fu has led me to several posts that explains that an ant script is needed to compile (eg link, link2, link3 ,and the one i ended on following: link4)
My project is a multi-module setup.
root build.gradle
subprojects {
apply plugin: 'java'
apply plugin: 'idea'
repositories {
mavenCentral()
}
}
supproject build.gradle
apply plugin:'application'
mainClassName = "dk.OfferFileEditor.OfferFileEditorProgram"
configurations {
antTask
}
dependencies {
compile 'org.json:json:20140107'
compile project(":Shared:HasOffers Api")
//dependencies for java2c
antTask files('../../lib/javac2-13.1.1.jar', '../../lib/asm4-all-13.1.1-idea.jar', '../../lib/forms_rt-13.1.1.jar')
antTask group: 'org.jdom', name: 'jdom', version: '1.1'
}
task compileJava(overwrite: true, dependsOn: configurations.compile.getTaskDependencyFromProjectDependency(true, 'jar')) {
doLast {
println 'using java2c to compile'
project.sourceSets.main.output.classesDir.mkdirs()
ant.taskdef name: 'javac2', classname: 'com.intellij.ant.Javac2', classpath: configurations.antTask.asPath
ant.javac2 srcdir: project.sourceSets.main.java.srcDirs.join(':'),
classpath: project.sourceSets.main.compileClasspath.asPath,
destdir: project.sourceSets.main.output.classesDir,
source: sourceCompatibility,
target: targetCompatibility,
includeAntRuntime: false
}
}
But even though the compilation is successfull, a Nullpointer exception is thrown the first time I try to access one of the fields the UI Designer created. So something is not being compiled correctly.
I'm probably missing some setting, but after unsuccesfully pouring several hours into forums and google I still haven't found any solution.
So I made this a lot more complicated than needs be.
To make it work you need to change two things in your project.
A setting in IDEA 13.1.5
Settings -> GUI Designer -> Generate GUI into: Java source code
This makes IntelliJ IDEA add 3 methods into the bottom of your forms:
$$$setupUI$$$()
$$$setupUI$$$()
$$$getRootComponent$$$()
If they are missing try recompiling your project after you change the setting.
Add the missing classes
Intellij has a jar called forms_rt.jar, and I found mine in {IntelliJ IDEA Root}\lib. And renamed it to "forms_rt-13.1.1.jar"
This needs to be included during compile time to your project. If you are using Gradle as I did you could copy it to {project root}/lib and add a flatfile repository like so:
repositories {
mavenCentral()
flatDir dirs: "${rootDir}/lib"
}
After that you need to include it in your project gradle file:
dependencies {
compile name: 'forms_rt', version: '13.1.1'
}
After that it should be possible to build it both in IntelliJ IDEA and Gradle.
IntelliJ IDEA 2019.1
I found this issue still exists. It's at least somehow documented now:
If your build actions are delegated to Gradle, GUI Designer will not generate Java source code.
So by disabling the according setting
Build, Execution, Deployment | Build Tools | Gradle | Runner | Delegate IDE build/run actions to gradle
I was able to build and run the project successfully. Note that I didn't need any other settings or additional libraries from the answers above. I let Generate GUI into be set to Binary class files.
The forms_rt library is in mavenCentral.
http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22forms_rt%22
Once you have configured IntelliJ to update the SourceCode it is sufficient to just add the library to the dependencies in your build.gradle.
dependencies {
compile 'com.intellij:forms_rt:7.0.3'
}
Idea 2019.2
It seems like IntelliJ changed the settings UI when updating from 2019.1 to 2019.2, as the menu entry mentioned by Tom isn't there anymore.
I got it fixed by setting Build and run using: to IntelliJ Idea. I also changed Run tests using: to IntelliJ Idea to avoid problems while testing.
Both settings are located under File | Settings | Build, Execution, Deployment | Build Tools | Gradle.
I figured out an updated version of the gradle build workaround for a new project - https://github.com/edward3h/systray-mpd/blob/master/build.gradle
Probably won't use the form designer again though.
These are the relevant parts:
repositories {
mavenCentral()
maven { url "https://www.jetbrains.com/intellij-repository/releases" }
maven { url "https://jetbrains.bintray.com/intellij-third-party-dependencies" }
}
configurations {
antTask
}
dependencies {
implementation 'com.jetbrains.intellij.java:java-gui-forms-rt:203.7148.30'
antTask 'com.jetbrains.intellij.java:java-compiler-ant-tasks:203.7148.30'
}
task compileJava(type: JavaCompile, overwrite: true, dependsOn: configurations.compile.getTaskDependencyFromProjectDependency(true, 'jar')) {
doLast {
project.sourceSets.main.output.classesDirs.each { project.mkdir(it) }
ant.taskdef name: 'javac2', classname: 'com.intellij.ant.Javac2', classpath: configurations.antTask.asPath
ant.javac2 srcdir: project.sourceSets.main.java.srcDirs.join(':'),
classpath: project.sourceSets.main.compileClasspath.asPath,
destdir: project.sourceSets.main.output.classesDirs[0],
source: sourceCompatibility,
target: targetCompatibility,
includeAntRuntime: false
}
}
The dependency versions for jetbrains libraries are found via https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html?from=jetbrains.org#using-intellij-platform-module-artifacts and https://www.jetbrains.com/intellij-repository/releases/

How can I add a linked source folder in Android Studio?

In Eclipse I can add a source folder to my Android project as a "linked source folder". How do I achieve the same thing in Android Studio?
Or is it possible to add an external folder to build in Gradle?
In your build.gradle file, add the following to the end of the Android node:
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
The right answer is:
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
Furthermore, if your external source directory is not under src/main, you could use a relative path like this:
sourceSets {
main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}
You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project
I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.
While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described in Exclude a class from the build in Android Studio.
Until Android Studio gets updated to support include/exclude directives for Android sources, symbolic links work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of symbolic links on Unix-like systems. Cygwin can also create these with a little coercion. See: Git symbolic links in Windows and How to make a symbolic link with Cygwin in Windows 7.
Here’s a complete Java module Gradle file that correctly generates and references the built artefacts within an Android multi-module application:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "net.ltgt.gradle:gradle-apt-plugin:0.15"
}
}
apply plugin: "net.ltgt.apt"
apply plugin: "java-library"
apply plugin: "idea"
idea {
module {
sourceDirs += file("$buildDir/generated/source/apt/main")
testSourceDirs += file("$buildDir/generated/source/apt/test")
}
}
dependencies {
// Dagger 2 and Compiler
compile "com.google.dagger:dagger:2.15"
apt "com.google.dagger:dagger-compiler:2.15"
compile "com.google.guava:guava:24.1-jre"
}
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
This is for Kotlin DSL (build.gradle.kts):
android {
sourceSets["main"].java.srcDirs("src/main/myDirectory/code/")
sourceSets["main"].resources.srcDirs("src/main/myDirectory/resources/")
// Another notation:
// sourceSets {
// getByName("main") {
// java.srcDirs("src/main/myDirectory/code/")
// resources.srcDirs("src/main/myDirectory/resources/")
// }
// }
}
If you're not using Gradle (creating a project from an APK, for instance), this can be done through the Android Studio UI (as of version 3.3.2):
Right-click the project root directory and pick Open Module Settings
Hit the + Add Content Root button (center right)
Add your path and hit OK
In my experience (with native code), as long as your .so files are built with debug symbols and from the same absolute paths, breakpoints added in source files will be automatically recognized.

Categories

Resources