Intellij + Gradle: properties file - java

My configuration:
Gradle installed via Homebrew (Mac OS), Intellij Idea 13.
Preferences:
"Use default Gradle wrapper"
and gradle home: /Users/my_username/.gradle
For the following project:
/
build.gradle
gradle.properties
The gradle.properties file contains a variable NAME = PJ.
I also have a gradle.properties under /Users/my_username/.gradle/gradle.properties having a variable TEST=Hello.
For the given task, gradle prints Hello and null
task hello << {
println TEST
println NAME
}
Which means that it does not read by default the gradle.properties in the same directory. Is it a normal behavior or do I miss something in path variable so can the build.gradle script can read it?
A work-around I found is to add:
file("gradle.properties").withInputStream {
stream -> new Properties().load(stream)
}
When I used android studio the .properties file of the same dir was automatically imported.
PS: Although TEST var gets printed I get a warning for Cannot resolve symbol. I saw around and this is typical error (?).

With gradle 2.0 it works perfectly fine:
$HOME/.gradle/gradle.properties
TEST=Hello
gradle.properties
NAME = PJ
build.gradle
task hello << {
println TEST
println NAME
}
When gradle hello run I get the following output:
:hello
Hello
PJ
BUILD SUCCESSFUL
Total time: 2.992 secs

Tested with intelliJ 13.1.4 built-in Gradle 1.7 and downloaded Gradle 2.0 and 2.1 version
Works fine. Make sure that path HOME/.gradle/ is set properly
gradle.properties:
TEST=Hello
NAME=PJ

Related

The filename or extension is too long for Maven [duplicate]

I have this error in eclipse helios:
Exception occurred executing command line.
Cannot run program "C:\Program Files (x86)\Java\jre6\bin\javaw.exe" (in directory "C:\Users\motiver\helios_workspace\TimeTracker"): CreateProcess error=206, The filename or extension is too long
I researched a bit but most of the issues were related to DataNucleus when working on Google App Engine. But I am not using anything remotely related to Google App Engine. I am doing a small project with Servlet 3.0 on JBOSS 6. I am using Hibernate 4.1.2 for ORM and RESTEasy to expose a web service. I created a util file that has a main() method that basically drops and re-creates the schema. I run the main() methos when I need a clean database for testing purposes. It worked fine on Tomcat 7 but it stopped working when I moved to JBoss 6.
Any hint or solution would be greatly appreciated.
There is no simple (as in a couple of clicks or a simple command) solution to this issue.
Quoting from some answers in this bug report in Eclipse.org, these are the work-arounds. Pick the one that's the least painful to you:
Reduce the classpath
Use directories instead of jar files
Use a packed jar files which contains all other jars, use the classpath variable inside the manifest file to point to the other jars
Use a special class loader which reads the classpath from a config file
Try to use one of the attached patches in the bug report document
Use an own wrapper e.g. ant
Update: After July 2014, there is a better way (thanks to #Brad-Mace's answer below:
If you have created your own build file instead of using Project -> Generate Javadocs, then you can add useexternalfile="yes" to the Javadoc task, which is designed specifically to solve this problem.
In intellij there is an option to 'shorten command line', select 'JAR manifest' or '#argFiles' would solve the problem, basically it will put your lengthy class path into a jar file or a temp file
I faced this problem today and I was able to solve it using this Gradle plugin
It's github url is this
IF you, like me, have no idea what Gradle is but need to run a backend to do your front end work, what you need to do is find the build.gradle file that is being called to start your BE server and add this to the top:
plugins {
id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
If you create your own build file rather than using Project -> Generate Javadocs you can add useexternalfile="yes" to the javadoc task, which is designed specifically to solve this problem.
I was running into this issue trying to execute a JPQL query in the Hibernate / JPA console of IntelliJ 2020.2
Adding this to my .idea/workspace.xml fixed it
<component name="PropertiesComponent">
...
<property name="dynamic.classpath" value="true"/>
...
</component>
Origin of the solution: https://youtrack.jetbrains.com/issue/IDEA-166929?_ga=2.167622078.1290412178.1604511702-23036228.1574844686
Answering my own question here so that the solution doesn't get buried in comments. I exported the project as a runnable jar from within eclipse and did a command line "java -jar MyJar.jar" and it works perfectly fine
This is not specifically for eclipse, but the way I got around this was by creating a symbolic link to my maven repository and pointing it to something like "C:\R". Then I added the following to my settings.xml file:
<localRepository>C:\R</localRepository>
The maven repository path was contributing to the length problems in my windows machine.
Try updating your Eclipse version, the issue was closed recently (2013-03-12). Check the bug report https://bugs.eclipse.org/bugs/show_bug.cgi?id=327193
Question is old, but still valid. I come across this situation often whenever a new member joins my team or a new code segment is added to existing code. Simple workaround we follow is to "Reduce the classpath" by moving up the directories.
As question mentioned, this is not specific to eclipse. I came across this issue in IntelliJ Idea 14 and 2018 as well.
After a long research, I found the solution is to set the
fork = false
in javc of ant build file.
<javac destdir="${build.dir}" fork="false" debug="on">
<classpath .../>
<src ... />
<patternset ... />
</javac>
This is how my ant build javac looks now. To learn about more on fork, please refer ant documentation.
In bug report Bug 327193 it is considered fixed, but it happen to me recently with Eclipse Kepler 4.3.2.
Please download patch for Eclipse Juno or newer:
https://bugs.eclipse.org/bugs/attachment.cgi?id=216593
After download back up existing
eclipse/plugins/org.eclipse.jdt.launching_3.*.jar
Copy and paste classes in the patch to org.eclipse.jdt.launching JAR
(replace existing files).
Restart Eclipse.
How many people sad above, there are a lot of plugins to gradle execute a by pass in this problem like:
plugins {
id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
or
plugins {
id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}
But the better solution that I found was kill the JVM process and everything is done.
Add below to your gradle file:
plugins {
`id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}
See https://plugins.gradle.org/plugin/com.github.ManifestClasspath
Try adding this in build.gradle (gradle version 4.10.x) file and check it out com.xxx.MainClass this is the class where your main method resides:
plugins {
id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
apply plugin: 'application'
application {
mainClassName = "com.xxx.MainClass"
}
The above change must resolve the issue, there is another way using script run.sh below could fix this issue, but it will be more of command-line fix, not in IntelliJ to launch gradle bootRun.
Try this:
java -jar -Dserver.port=8080 build/libs/APP_NAME_HERE.jar
To solve it:
If you are using Eclipse:
Move .m2 repository to
c:\
Go to Eclipse > Windows/Preferences/Maven/User Settings -> Create your own setting.xml with its content:
<settings>
<localRepository>c:/.m2/repository</localRepository>
</settings>
If you are using IntelliJ:
Go to IntelliJ > clicking the right mouse button on "pom.xml" > maven > create "settings.xml"
with its content:
<settings>
xmlns="yourcontent"
xmlns:xsi="yourcontent"
xsi:schemaLocation="yourcontent.xsd">
<localRepository>c:/.m2/repository</localRepository>
</settings>
In my case the error was showing because system java version was different from intellijj/eclipse java version. System and user had diff java versions. If you compile your code using one version and tried to run using a different version, it will error out.
#The system java version is 1.7.131
$ java -version
java version "1.7.0_131"
Long story short, make sure your code is compiled and ran by the same java version.
I am using legacy version of gradle plugins and this plugin solved the issue for me.
Usage (check source for more details):
Build script snippet for plugins DSL for Gradle 2.1 and later
plugins {
id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}
Build script snippet for use in older Gradle versions or where dynamic
configuration is required
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.github.viswaramamoorthy:gradle-util-plugins:0.1.0-RELEASE"
}
}
apply plugin: "com.github.ManifestClasspath"
I have got same error, while invoking Maven.
The root cause for my problem was the classpath was very huge. Updating the classpath fixed the problem.
There are multiple ways to update the large classpath as mentioned in this: How to set a long Java classpath in Windows?
Use wildcards
Argument File
Pathing jar
Since I am using Intellij, they provide the option to use Argument File that i used.
In a Windows machine, there is a limitation of the jar file name/path length in the command-line, due to which you see the below error message, I tried searching a lot, even I tried applying the above solution, some reason, it didn't work, I found the working snippet for Gradle (gradle-4.10.2-all.zip)
Error:
CreateProcess error=206, The filename or extension is too long
Use this below gradle.build code snippet to fix the above problem in IntelliJ or STS, or eclipse anything.
Gradle Code Fix:
apply plugin: 'application'
task pathingJar(type: Jar) {
dependsOn configurations.runtime
appendix = 'pathing'
doFirst {
manifest {
attributes "Class-Path": configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')
}
}
}
task copyToLib(type: Copy) {
into "$buildDir/libs"
from configurations.runtime
}
bootRun {
systemProperties = System.properties
//This below line is for if you have different profiles prod, dev etc...
//systemProperty 'spring.profiles.active', 'dev'
jvmArgs('-Djava.util.logging.config.file=none')
mainClassName = "com.xxxx.Main"
dependsOn pathingJar
dependsOn copyToLib
doFirst {
classpath = files("$buildDir/classes/java/main", "$buildDir/resources/main", pathingJar.archivePath)
}
}
If you are using VSCode:
create launch.json file insde .vscode/
add
{"configurations": [{ "type": "java","shortenCommandLine ": "auto",}]}
If you are using intellij :
open .idea/workspace.xml
inside <component name="PropertiesComponent">
add <property name="dynamic.classpath" value="true"/>
it happens due to DataNucleus sometimes overwrite the Arguments with many paths.
You have to overwrite them with this:
-enhancerName ASM -api JDO -pu MediaToGo
Hope help you!
I got the same error. Tried solutions like cleaning, rebuild, invalidateCache, retart etc but nothing works.
I just have created a new folder with short name and copied all the files(app folder, gradle files etc) in new folder. Opened application in android studio and its working fine.
For me it was wrong JDK path. Please make sure you have right path to the JDK file
File -> Project Structure
If you are using Android Studio try Invalidate Caches/ Restart.. option present in File menu
I used com.virgo47.ClasspathJar plugin to fix this issue
https://plugins.gradle.org/plugin/com.virgo47.ClasspathJar
To fix this below error, I did enough research, not got any great solution, I prepared this script and it is working fine, thought to share to the public and make use of it and save there time.
CreateProcess error=206, The filename or extension is too long
If you are using the Gradle build tool, and the executable file is placed in build/libs directory of your application.
run.sh -> create this file in the root directory of your project, and copy below script in it, then go to git bash and type run.sh then enter. Hope this helps!
#!/bin/bash
dir_name=`pwd`
if [ $# == 1 ] && [ $1 == "debug" ]
then
port=$RANDOM
quit=0
echo "Finding free port for debugging"
while [ "$quit" -ne 1 ]; do
netstat -anp | grep $port >> /dev/null
if [ $? -gt 0 ]; then
quit=1
else
port=`expr $port + 1`
fi
done
echo "Starting in Debug Mode on "$port
gradle clean bootjar
jar_name="build/libs/"`ls -l ./build/libs/|grep jar|grep -v grep|awk '{print $NF}'`
#java -jar -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$port $jar_name
elif [ $# == 1 ] && [ $1 == 'help' ]
then
echo "please use this commands"
echo "------------------------"
echo "Start in Debug Mode: sh run.sh debug"
echo "Start in Run Mode: sh run.sh"
echo "------------------------"
else
gradle clean bootjar
word_count=`ls -l ./build/libs/|grep jar|grep -v grep|wc -w`
jar_name=`ls -l ./build/libs/|grep jar|grep -v grep|awk '{print $NF}'`
jar_path=build/libs/$jar_name
echo $jar_name
#java -jar $jar_path
fi
Hope this helps!!
You can use below commands:
mklink /J c:\repo C:\<long path to your maven repository>
mvn -Dmaven.repo.local=c:\repo any mvn command
Valid answer from this thread was the right answer for my special case.
Specify the ORM folder path for datanucleus certainly reduce the java path compile.
https://stackoverflow.com/a/1219427/1469481
I got the error below when I run 'ant deploy'
Cannot run program "C:\java\jdk1.8.0_45\bin\java.exe": CreateProcess error=206, The filename or extension is too long
Fixed it by run 'ant clean' before it.
I got the same error in android studio. I was able to resolve it by running Build->Clean Project in the IDE.

Setting build properties in Android Gradle via Jenkins

How do you tell Jenkins to set a property inside gradle.properties in an Android project? I've figured out how to get the properties from Gradle into Jenkins (by using the EnvInject plugin and simply entering gradle.properties into the property file field) but I also want the build number that is managed by Jenkins to be injected into the build artifact.
I also want to set the filename of the resulting artifact which, I think, needs to be injected by using archivesBaseName. But that property isn't part of gradle.properties so I wonder how do I access it?
So far I've only found solutions that change the build.gradle file (or other gradle scripts) in the Android project itself. But that's not what I want to do because that would make the Android code base rely on Jenkins.
Instead I want Jenkins to provide the build number and artifact file name to the Android project before it compiles the code.
The server runs on a Mac. Does anyone have a solution for this? Any shell/Groovy script that does the job would be welcome.
We are just wrinting a file version.properties, which is generated by jenkins "echo "VERSION_CODE=${BUILD_NUBMER}" > version.properies" script.
Then gradle script imports it as following:
// Version code is loaded from a properties file
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger()
versionCode code
}
else {
throw new GradleException("Could not read version.properties!")
}
buildConfigField "String", " some _VERSION", "\"${getVersionString()}\""
}

How to set project.version by passing version property on gradle command line?

I want to build JAR with self-defined version passed via command line, such as:
When I execute gradle build task like this:
gradle build -Pversion=1.0
myproject-1.0.jar should be generated.
I have tried adding the line below to the build.gradle, but it did not work:
version = project.hasProperty('version') ? project['version'] : '10.0.0'
Set the property only in the gradle.properties file (i.e. remove it from build.gradle). Also make sure the options come before the command (as mentioned above).
gradle.properties contents:
version=1.0.12
Version can then be overridden on the command line with:
gradle -Pversion=1.0.13 publish
You are not able to override existing project properties from command line, take a look here. So try to rename a version variable to something differing from version and set it with -P flag before command, like:
gradle -PprojVersion=10.2.10 build
And then in your build.gradle
if (project.hasProperty('projVersion')) {
project.version = project.projVersion
} else {
project.version = '10.0.0'
}
Or as you did with ?: operator
If you move version entry to gradle.properties file you can also:
gradle clean build -Dorg.gradle.project.version=1.1
You can pass the project version on cli with -Pversion=... as long as you don't set it in build.gradle. If you need a custom default value for when no version is passed on the cli, use gradle.properties file like so: version=...
TL;DR: Don't set the version in build.gradle file if you want to change it later on via cli.
If you need a default version other than 'unspecified':
version = "${version != 'unspecified' ? version : 'your-default-version'}"
Pass version via command line:
gradle build -P version=1.0
version = (findProperty('version') == 'unspecified') ? '0.1' : version
I've found this to be the easiest and cleanest way, without requiring a gradle.properties file or changing the version variable name.
In build.gradle:
// Note - there is intentionally no equals sign here
version project.hasProperty('version') ? version : '1.0.0'
From the command line:
./gradlew -Pversion=1.5.2 build

Store method parameter names for some classes when building with Gradle/Java8

Follow up question to this question.
How do I store method parameter names for classes when building with Gradle (build.gradle file)?
According to Java tutorials:
To store formal parameter names in a particular .class file, and thus
enable the Reflection API to retrieve formal parameter names, compile
the source file with the -parameters option to the javac compiler.
So How do I pass the "-parameters" to the javac compiler using Gradle?
I tried the suggested solution here, by adding the below into my build.gradle file with no luck.
apply plugin: 'java'
compileJava {
options.compilerArgs << '-parameters'
options.fork = true
options.forkOptions.executable = 'javac'
}
I'm using eclipse and if I enable this (in Window -> Preferences -> Java -> Compiler), it works fine.
Store information about method parameters (usable via reflection)
But I would rather have this setting set by my build system, so i don't depend on eclipse and so others can use my buildt .jar files.
I use:
Eclipse 4.4.2
Gradle IDE 3.6.4 (eclipse plugin)
To get gradle itself to compile with -parameters add the following to your build.gradle:
compileJava.options.compilerArgs.add '-parameters'
compileTestJava.options.compilerArgs.add '-parameters'
In order to use Gradle to generate Eclipse project files where -parameters is set for javac: Use a tip from this gradle forum post and add the following to your build.gradle:
eclipseProject {
doLast {
// https://discuss.gradle.org/t/how-to-write-properties-to-3rd-party-eclipse-settings-files/6499/2
def props = new Properties()
file(".settings/org.eclipse.jdt.core.prefs").withInputStream {
stream -> props.load(stream)
}
props.setProperty("org.eclipse.jdt.core.compiler.codegen.methodParameters", "generate")
file(".settings/org.eclipse.jdt.core.prefs").withOutputStream {
stream -> props.store(stream, null)
}
}
}
(Apparently a) the Gradle Eclipse plugin doesn't know how to translate the compiler option -parameters to the .settings/org.eclipse.jdt.core.prefs setting org.eclipse.jdt.core.compiler.codegen.methodParameters=generate and b) there's no standard Gradle task that manipulates any of the property files in .settings, so you've got to roll your own.)
This is for Gradle 2.8.
sourceCompatibility=1.8
[compileJava, compileTestJava]*.options*.compilerArgs = ['-parameters']
After some research for the same problem, one solution is to make something like this: https://github.com/codeborne/mobileid/blob/master/build.gradle
Add this to your build.gradle:
[compileJava, compileTestJava]*.options.collect {options ->
options.compilerArgs.add '-parameters'
}
It works for me with gradle 2.4

Can't execute debug task in NetBeans after switching to Gradle

I've installed the Gradle-support plugin in Netbeans and I can build and run the project just fine. When I try to run in debug mode, I get the following output:
Executing: gradle debug
:debug
Cannot execute debug because the property "mainClass" is not defined or empty.
BUILD SUCCESSFUL
Total time: 0.222 secs
I'm using:
Oracle Java 1.8
Gradle 1.12
Netbeans 8.0
Gradle-Support 1.3.0
LinuxMint 16
Why can't I run my debugger?
Add something like
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.foo.acme.Main'
}
to your build.gradle. It will tell Gradle plugin what class to use when starting your application. Perhaps that should be customizable in the UI but I cannot see it now.
Another solution to this problem is to create a new debug task. Similar to the gradle run task you can just add the following task to your build.gradle file:
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
In addition to Radim's answer the way to customize the mainClass parameter in the Netbeans UI.
In the properties of a Netbeans gradle project go to "Built-In Tasks/Debug", unclick the "Inherit" and add "-PmainClass=aaa.bbb.ccc" to the arguments.
I guess this should also be done for the run task.
It's the same idea like run/debug single file which already take the selected file as parameter mainClass.
I had a similar problem and was able to fix it setting Options / Miscellaneous / Gradle / Task Execution / Automatic tasks to "NetBeans should not add tasks automatically".

Categories

Resources