Java: Connect Gradle with Velocity - java

I'm trying to connect Velocity with Gradle builder. So I created a Gradle project in IntelliJ, put the Gradle-Velocity-Plugin into the project directory, imported the Velocity jar and created the following files:
build.gradle:
group 'xxxxx'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.5
repositories {
mavenCentral()
jcenter()
}
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'org.anarres.gradle:gradle-velocity-plugin:[1.0.0,)'
}
}
apply plugin: 'velocity'
jar {
manifest {
attributes 'Main-Class': 'test.HelloWorld'
}
}
HelloWorld.java:
package test;
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
public class HelloWorld
{
public static void main(String[] args)
{
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext context = new VelocityContext();
context.put("name", "World");
Template t = ve.getTemplate( "helloworld.vm" );
StringWriter writer = new StringWriter();
t.merge( context, writer );
System.out.println( writer.toString() );
}
catch (Exception e) {
System.out.println("failed");
}
}
}
Now, when I execute gradle tasks, everything is fine, but when I execute gradle assemble, I get errors, that the velocity packages do not exist.
Does anyone of you got an idea how to fix this?
Thank you.

Related

api configuration of java-library plugin is not recognized

I am new to Gradle and i am using Gradle 6.1.
I am writing small application to understand the concepts of multi project Application and Java-Library plugin of Gradle.
My Question is :
How App.java is running perfectly fine without importing DefaultRandomGenerator class from SubProject-2
Why am i getting the error message "No candidates found for method call api" in build.grade file of Parent project (MultiProjectApp).
Below are my application code :
Parent Project (MultiProjectApp) files
settings.gradle
rootProject.name = 'MultiProjectApp'
include 'SubProject-1'
include 'SubProject-2'
build.gradle
allprojects {
apply plugin: 'java'
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
}
project(':SubProject-1') {
dependencies {
implementation project(':SubProject-2')
}
}
project(':SubProject-2') {
apply plugin: 'java-library'
dependencies {
api 'org.apache.commons:commons-math3:3.2'
implementation 'org.apache.logging.log4j:log4j-core:2.5'
testImplementation "junit:junit:4.12"
}
}
SubProject-2 files
build.gradle
Empty file
RandomGenerator.java
package org.examples;
public interface RandomGenerator {
String name();
int generate();
}
DefaultRandomGenerator.java
package org.examples;
import org.apache.commons.math3.random.RandomDataGenerator;
public class DefaultRandomGenerator implements RandomGenerator {
public String name() {
return "Main Random Number Generator";
}
public int generate() {
final RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
return randomDataGenerator.nextInt(5, 10);
}
}
SubProject-1 files
build.gradle
Empty file
App.java
package org.examples;
import org.apache.commons.math3.random.RandomDataGenerator;
public class App {
public static void main(String[] args) {
RandomGenerator aRandomGenerator = new DefaultRandomGenerator();
System.out.println("The 1st random number is :" + aRandomGenerator.generate());
System.out.println("The 2nd random number is :" + generateMy());
}
public static int generateMy() {
final RandomDataGenerator aRandomDataGenerator = new RandomDataGenerator();
return aRandomDataGenerator.nextInt(5, 10);
}
}
How App.java is running perfectly fine without importing
DefaultRandomGenerator class from SubProject-2
It works because they are both in the same package (org.examples).
Note that this will not work if using the new module system introduced in Java 9. Because the two projects are considered "split", and you will need various hacks to make it work.
Why am I getting the error message "No candidates found for method
call api" in build.grade file of Parent project (MultiProjectApp).
This is an IDE problem, not a gradle problem. If you run, it should still work.
Example of runnig it in Vscode

Assets not being loaded (libGDX)

So I've made a small desktop application in Eclipse (gradle project) based on libGDX. Runs perfectly in Eclipse. When I export as a "runnable JAR file" (with Package required libraries into generated JAR checked) I get a warning: "Fat Jar Export: Could not find class-path entry for 'D:Project TI Helper/core/bin/default/".
Is something missing in the manifest at "Class-Path: ." ?
I have no idea what this is about. But the JAR is certainly not runnable. So I try the command prompt and do "gradle desktop:dist --stacktrace". Then the JAR file seems to be produced without any errors or warnings. So I go to .../desktop/build/libs/ and try to run it with "java -jar desktop-1.0.jar", the texture packer starts packing but fails in the end with this message in the console.
The generated atlas-file IS in the specified location. The textures WERE packed. Why on earth is it not loading the stuff?? Btw, I'm using Java version 1.8.0_241 for both JDK and JRE.
EDIT
So it fails in the Assets class at "TextureAtlas atlas = assets2d.get(Cn.TEXTURES);". Going deeper into the AssetManager
public synchronized <T> T get (String fileName) {
Class<T> type = assetTypes.get(fileName);
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
...
So it seems the string provided is not pointing to my atlas-file. Cn.TEXTURES is defined as "../desktop/assets/atlas/textures.atlas". That raises the question: How DO you write the path?
DesktopLauncher.java
public class DesktopLauncher
{
public static boolean rebuildAtlas = true;
public static boolean drawDebugOutline = true;
public static void main (String[] arg)
{
// Build Texture Atlases
if (rebuildAtlas) {
Settings settings = new Settings();
settings.maxWidth = 2048;
settings.maxHeight = 2048;
settings.pot = false;
settings.combineSubdirectories = true;
// Pack images in "textures" folder
TexturePacker.process("assets/textures", "assets/atlas", "textures.atlas");
}
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "TI Helper";
cfg.useGL30 = false;
cfg.width = Cn.RESOLUTION_WIDTH;
cfg.height = Cn.RESOLUTION_HEIGHT;
cfg.fullscreen = true;
new LwjglApplication(new TIHelper(), cfg);
}
}
Assets.java
public class Assets implements Disposable, AssetErrorListener
{
public static final String TAG = Assets.class.getName();
public static final Assets instance = new Assets();
// Asset managers
public AssetManager assets2d;
public AssetDeco assetDeco;
public AssetFonts fonts;
public AssetMisc assetMisc;
// General fonts
public static Font not16, not20, not24, dig16;
// Singelton: prevent installation from other classes
private Assets() {}
public void init ()
{
// Init 2D graphics manager
init2DAssetManager();
TextureAtlas atlas = assets2d.get(Cn.TEXTURES);
// Cn.TEXTURES == String TEXTURES = "../desktop/assets/atlas/textures.atlas";
// Create game resource objects
fonts = new AssetFonts();
assetDeco = new AssetDeco(atlas);
assetMisc = new AssetMisc(atlas);
// Create fonts
not16 = new Font(Assets.instance.fonts.notalot_16);
not20 = new Font(Assets.instance.fonts.notalot_20);
not24 = new Font(Assets.instance.fonts.notalot_24);
dig16 = new Font(Assets.instance.fonts.digits_16);
}
private void init2DAssetManager()
{
// Create the manager
assets2d = new AssetManager();
// Set asset manager error handler
assets2d.setErrorListener(this);
// Load texture atlas
assets2d.load(Cn.TEXTURES, TextureAtlas.class);
// Start loading assets and wait until finished
assets2d.finishLoading();
// Prompt output
Gdx.app.debug(TAG, "# of assets loaded: " + assets2d.getAssetNames().size);
for (String a : assets2d.getAssetNames())
Gdx.app.debug(TAG, "asset: " + a);
}
#Override
public void dispose ()
{
assets2d.dispose();
}
public void error (String filename, Class<?> type, Throwable throwable) {
Gdx.app.error(TAG, "Couldn't load asset '" + filename + "'", (Exception)throwable);
}
...
Desktop build.gradle
apply plugin: "java"
sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = [ "src/" ]
sourceSets.main.resources.srcDirs = ["../desktop/assets"]
project.ext.mainClassName = "com.ti.desktop.DesktopLauncher"
project.ext.assetsDir = new File("../desktop/assets")
task run(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
task dist(type: Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
}
dist.dependsOn classes
eclipse.project.name = appName + "-desktop"
Workspace build.gradle
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
jcenter()
google()
}
dependencies {
}
}
allprojects {
apply plugin: "eclipse"
version = '1.0'
ext {
appName = "ti-helper"
gdxVersion = '1.9.10'
roboVMVersion = '2.3.8'
box2DLightsVersion = '1.4'
ashleyVersion = '1.7.0'
aiVersion = '1.8.0'
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
google()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "https://oss.sonatype.org/content/repositories/releases/" }
}
}
project(":desktop") {
apply plugin: "java-library"
dependencies {
implementation project(":core")
api "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
api "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
api "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
api "com.badlogicgames.gdx:gdx-tools:$gdxVersion"
api "com.badlogicgames.gdx:gdx-controllers-desktop:$gdxVersion"
api "com.badlogicgames.gdx:gdx-controllers-platform:$gdxVersion:natives-desktop"
}
}
project(":core") {
apply plugin: "java-library"
dependencies {
api "com.badlogicgames.gdx:gdx:$gdxVersion"
api "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
api "com.badlogicgames.gdx:gdx-controllers:$gdxVersion"
api "net.dermetfan.libgdx-utils:libgdx-utils:0.13.4"
api "net.dermetfan.libgdx-utils:libgdx-utils-box2d:0.13.4"
}
}
If someone could help me out it would much appreciated. This is my first project in libGDX and I'm very stuck here, and I'm all out of ideas on how to find any clues to what might be wrong.
I just had the same issue and removing the ".atlas" from the filename fixed it. Although that is the file type, when I open my atlas file's properties in Windows explorer, the file type is simply listed as "file" rather than atlas.

Could not import third-party class in gradle file other than build.gradle

I want to import a third-party class org.ajoberstar.grgit.Grgit in a gradle file version.gradle. However it is giving me the error that it is unable to resolve class org.ajoberstar.grgit.Grgit(I am using apply from: "version.gradle" in build.gradle). But if I import it in build.gradle, it works fine. Here is what I am doing:
build.gradle:
plugins {
id "org.ajoberstar.grgit" version "1.5.0"
}
apply from: "version.gradle"
// Version of jar file.
version = 1.0
jar
{
destinationDir = file(JAR_DIR)
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'com.awesomeness.Main'
}
}
jar.dependsOn versionTxt
// Artifact dependecies.
dependencies {
compile files("$TOOLS/lib/grgit-1.5.0.jar")
compile files("$TOOLS/lib/groovy-all-2.4.7.jar")
compile files("$TOOLS/lib/org.eclipse.jgit-4.2.0.201601211800-r.jar")
}
Here is the version.gradle file:
import org.ajoberstar.grgit.Grgit
//
import java.text.DateFormat
task versionTxt() {
doLast {
Grgit grgit = Grgit.open()
File file = new File("$buildDir/version.txt")
file.write("")
file.append("Version: $version")
file.append("Branch: "+grgit.branch.current.trackingBranch.name)
file.append("Build-Type: ")
file.append("Build-Date: " + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date((long)grgit.head().time*1000l)))
file.append("Commit-Id: "+ grgit.head().abbreviatedId)
}
}
I tried a few SO links like:
How can I import one Gradle script into another?
Gradle dependencies not working (Cannot import)
How do I import a class in gradle outside of build.gradle in a apply from: file
But I could not resolve this. Any help?
You need to make the org.ajoberstar.grgit package classes available in the Gradle script where you use it, using buildscript block:
version.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath("org.ajoberstar:grgit:1.5.0")
}
}
import org.ajoberstar.grgit.Grgit
// .. rest of your build script

Gradle NoClassDefFoundError when running jar

I'm trying to set up a Gradle project with some Velocity functions in it.
So far I have the following files:
src/main/java/com/veltes/velotest.java:
package com.veltes;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.*;
public class velotest {
public static void main(String[] args) {
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext context = new VelocityContext();
context.put("name", "World");
Template t = ve.getTemplate("com/veltes/velotest.vm");
StringWriter writer = new StringWriter();
t.merge(context, writer);
System.out.println(writer.toString());
File logFile = new File("C:/users/xxxx/Desktop/velotest.html");
try {
writeFile(logFile, t, context);
}
catch (IOException io) {
}
} catch (Exception e) {
}
}
private static void writeFile(File logFile, Template t, VelocityContext context) throws IOException {
Writer logWriter;
logWriter = new BufferedWriter(new FileWriter(logFile));
try {
t.merge(context, logWriter);
}
catch (ResourceNotFoundException rnfe) {
}
catch (ParseErrorException pee) {
}
catch (MethodInvocationException mie) {
}
catch (Exception e) {
}
logWriter.flush();
logWriter.close();
}
}
build.gradle:
group 'velocitytest'
version '1.0-SNAPSHOT'
apply plugin: 'groovy'
apply plugin: 'java'
sourceCompatibility = 1.5
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.11'
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'velocity:velocity:1.4'
}
Now, when I run gradle assemble and gradle build everything is fine, but when I try to run the project (same for running the built jar in build/libs/ and for running the velotest class in IntelliJ), I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/ExtendedProperties
at org.apache.velocity.runtime.RuntimeInstance.< init >(RuntimeInstance.java:183)
at org.apache.velocity.app.VelocityEngine.(VelocityEngine.java:60)
at com.veltes.velotest.main(velotest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.ExtendedProperties
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more
It's a bit strange that there is no jar in build/tmp/
Does anyone of you knows a solution?
You need to create a runnable jar if you want to be able to run it.
You can use shadojar plugin or extend the jar task to pack the runtime deps into an artifact.
jar {
archiveName = 'Name.jar'
manifest {
attributes 'Main-Class': 'your.main.class',
'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' '),
'Implementation-Version': project.version
}
from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {}
}
For intelliJ problem:
apply plugin: 'idea'
Then run gradle idea task, this will refresh .iws .ipr .iml files in your project and sync the classpaths. Or if you use intelliJ support (which is not yet ideal) try to refresh it there. I think in version 2017.1.3 the gradle integration is a bit better.
Adding
from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {} to build.gradle file fixed it for me, like this:
jar {
manifest {
attributes(
'Main-Class': 'gradle22.Library'
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}

Spring MVC won't load static content

I am new to Spring and i want to load some css and js into a view.
The static content is now in src/main/resources/static/... but when i navigate to localhost:8080/css/test.css it gives me a 404 error..
I don't use any xml configuration files.
My project structure:
Update: Application class
package com.exstodigital.photofactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Update: build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
}
}
group 'PTS4'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-devtools")
testCompile("junit:junit")
}
Some controller (just testing stuff):
package com.exstodigital.photofactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
//#Controller
public class MainController {
//#ResponseBody
#RequestMapping("/greeting/{name}/{hoi}")
public String greeting(#PathVariable("name") String name, #PathVariable("hoi") String hoi) {
//model.addAttribute("message", "BERICHT");
return name;
}
#RequestMapping("/test")
public String test() {
return "test";
}
}
Your structure is correct. Don't forget to make gradle clean task before run bootRun.

Categories

Resources