I have built a new basic grails project. I have a basic java object I've written outside of grails, and jarred up. I've added the jar file to the grails project, via the properties > Java build path > Libraries tab > Add Jars.
Then I try to access it in a grails controller, and get a class def not found error.
What am I doing wrong?
TestController.groovy
package testproject
import test.TestClass
class TestController {
def index() {
def testClass = new TestClass()
render 'Index page'
}
}
and:
in the jar, TestClass.java
package test;
public class TestClass {
private String string;
public void setString(String string)
{
this.string = string;
}
public String getString()
{
return string;
}
}
The error is:
C:\Users\One\TestProject\grails-app\controllers\testproject\TestController.groov
y: 3: unable to resolve class test.TestClass # line 3, column 1.
import test.TestClass
The STS classpath generated from the Grails classpath, but it's unidirectional. Adding items in STS has no effect on Grails.
Put the jar file in your lib directory and run grails compile --refresh-dependencies. Then re-sync STS from Grails by right-clicking the project node in the tree and running Grails Tools | Refresh Dependencies.
You still need to import it in the Grails controller.
import your.java.ClassName
Related
I'm attempting to create unit tests for a JenkinsShared library using Gradle in order to run the test tasks.
I've followed this tutorial which upon conclusion one has a working test suite for a shared library for functions within the vars folder (with the unit tests in src/test/groovy/*Test.groovy).
However, in our internal shared jenkins library we followed a more object oriented style and isolated functionality into a package of classes in the format: src/org/company/*.groovy.
The problem arises when attempting to import said package into a unit test class. In the tutorial, the functions are imported using the loadScript method this method fails when loading a class which is dependent on another file.
Take the class:
package tests
import org.junit.*
import com.lesfurets.jenkins.unit.*
import static groovy.test.GroovyAssert.*
import org.company.UtilFactory
class UtilFactoryTest extends BasePipelineTest {
#Test
void testCall() {
def util = UtilFactory.getUtil("hello")
assertEquals true, true
}
}
src/org/company/UtilFactory.groovy
package org.company
class UtilFactory implements Serializable {
static Util instance
static Util getUtil(script=null) {
if (!(UtilFactory.instance)) {
if (!script) {
// Throws an exception if on the first call to getUtil the
// script parameter is null.
throw new ScriptUndefinedException("script parameter null on initial call to getUtil")
}
UtilFactory.instance = new Util(script)
}
return UtilFactory.instance
}
}
class ScriptUndefinedException extends Exception {
// Parameterless Constructor
public ScriptUndefinedException() {}
// Constructor that accepts a message
public ScriptUndefinedException(String message)
{
super(message);
}
}
Which gives me the exception:
jenkins-utilities/src/test/groovy/UtilFactoryTest.groovy: 7:
unable to resolve class org.company.UtilFactory
# line 7, column 1.
import org.company.UtilFactory
This may be more of a Gradle issue than a JenkinsShared Library. I've just spent a good portion of my day trying to figure out exactly what I'm doing wrong to no avail.
I would really appreciate any help to guide me in the right direction.
This library may be helpful getting your shared libraries to work in the unit test https://github.com/stchar/pipeline-sharedlib-testharness
I'm using grails 3.3.0 with rest api and gson views. I have the following setup...
Domain Class
package foo
#Resource(uri="/api/bars", readOnly = false, formats = ['json', 'xml'])
class Bar{
String firstName
String lastName
}
Controller:
package foo
class BarController extends RestfulController<Building>{
def show(){
respond Bar.get(params.id)
}
}
_bar.gson:
import foo.Bar;
model {
Bar bar
}
json {
name bar.firstName
}
_show.gson:
import foo.Bar;
model {
Bar bar
}
json g.render(template:"bar", model:[bar:bar])
directory layout:
/grails-app/views/
-----------------bar/
--------------------_bar.gson
--------------------_show.gson
This fails during build, test, compile and war with the following error:
Execution failed for task ':compileGsonViews'.
foo_bar_show_gson: 3: unable to resolve class foo.Bar
I followed the documentation but I cannot get around this. Please help!
I have the same issue, my problem got solved when I change the views-gradle version to the 1.2.7
classpath "org.grails.plugins:views-gradle:1.2.7"
After looking through github issues this seems to be caused by the rest profile and running on a Windows machine. If I start a new project using the web profile everything works fine.
There is no grails.config.locations property in grails 3 anymore, now Grails 3 uses Spring's property source concept instead, but how can I achieve the same behavior in grails 3 as it was in previous versions? Suppose I want to override some property property.to.be.overridden in application.grovy file with my external configuration file. How can I do it?
The equivalent of grails.config.locations is spring.config.location
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files
Here is an example specifying configuration locations while launching a jar from the command line(These same arguments can be used inside of your ide)
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
Also since you mention wanting to override properties it's useful to learn the way Spring Boot handles profile specific property files(Multiple profiles may also be specified)
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties
I solved this a slightly different way, so I could load an external YAML file.
Application.groovy
package com.mycompany.myapp
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.core.env.PropertiesPropertySource
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.Resource;
class Application extends GrailsAutoConfiguration implements EnvironmentAware {
static void main(String[] args) {
GrailsApp.run(Application)
}
#Override
void setEnvironment(Environment environment) {
String configPath = System.properties["myapp.config.location"]
if (configPath) {
Resource resourceConfig = new FileSystemResource(configPath);
YamlPropertiesFactoryBean propertyFactoryBean = new YamlPropertiesFactoryBean();
propertyFactoryBean.setResources(resourceConfig);
propertyFactoryBean.afterPropertiesSet();
Properties properties = propertyFactoryBean.getObject();
environment.propertySources.addFirst(new PropertiesPropertySource("myapp.config.location", properties))
}
}
}
Then I specify the YAML file when I run it
command line
java -jar -Dmyapp.config.location=/etc/myapp/application.yml build/libs/myapp-0.1.war
I'm playing around with Grails/Groovy and have some straight Groovy code working that utilizes groovy-wslite. That code starts as such
send-request.groovy
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0')
import wslite.soap.*
When I implement that into my Grails code and view the controller/action I get this
Error 500: Internal Server Error
URI: /FormProj/hello/trigger
Class: java.lang.RuntimeException
Message: No suitable ClassLoader found for grab
And here's the code in it's current state (I've tried a LOT of different things)
HelloController.groovy
package com.demo
import groovy.grape.Grape
class HelloController {
def index() { }
def sayHi() {
return [
greeting : "Hi there, ${ params.name }"
]
}
def trigger() {
Grape.grab(group:'com.github.groovy-wslite', module:'groovy-wslite', version:'1.1.0')
…
}
}
As I'm sure you notice I'm very green with Grails/Groovy and really all things Java. I do know there is a wslite plugin for Grails, but surely this can work too right?
Grails: 2.3.8
Groovy: 2.2.2
UPDATE
Based on Ian Robert's advice I have updated my BuildConfig file by adding this line to the dependencies block
compile 'com.github.groovy-wslite:groovy-wslite:1.1.0'
And updated my controller to look like this
HelloController.groovy
package ws.thejspot
import wslite.soap.*
class HelloController {
def index() { }
def sayHi() {
return [
greeting : "Hi there, ${ params.name }"
]
}
def trigger() {
def client = new SOAPClient('URL')
}
}
Unfortunately now the IDE, GGTS, shows an error in the controller 'unable to resolve class SOAPClient'
Rather than trying to download the dependencies with #Grab, you should use the standard Grails dependency mechanism - edit grails-app/conf/BuildConfig.groovy and look for the grails.project.dependency.resolution closure. Inside that, in the dependencies block you should add
compile 'com.github.groovy-wslite:groovy-wslite:1.1.0'
and remove anything Grape-related from the controller, leaving just the import wslite.soap.*
You will probably need to run
grails compile --refresh-dependencies
at least once to ensure that Grails picks up your change to BuildConfig - it deliberately doesn't do a full dependency resolve every time you compile, so as not to slow down the build too much, so you need to tell it to refresh when you know it needs to.
I'm studying Grails framework and developing an application.
At the moment I have a main application which has severals plugins.
So the hierarchy is like that :
MyMainApp
MyFirstPlugin
MySecondPlugin
...
I would like to write UrlMappings tests for my plugins. I wrote the doc and I'm probably missing something but I can't pass those f** tests. I always catch the error
java.lang.IllegalArgumentException: url '/bar' did not match any mappings
Here is my FooUrlMappings class
class FooUrlMappings {
static mappings = {
"/bar/"(controller: 'foo', action: 'show')
}
}
Note that my FooUrlMappings class is in the default package in /conf directory.
Now the code of my controller FooController :
package be.arexo.ehr.employee.rest
import be.arexo.ehr.employee.Employee
import grails.converters.JSON
class FooController {
// GET /bar/
def show() {
def result = Bar.list()
render result as JSON
}
}
So now, my test class :
import com.example.FooController
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import grails.test.mixin.web.UrlMappingsUnitTestMixin
#TestFor(FooUrlMappings)
#Mock(FooController)
class FooUrlMappingsTests {
void testBarShow(){
assertForwardUrlMapping("/bar/", controller : "foo", action : "show")
}
}
My test is also in the default package in the test/integration directory.
So I think that I did what is said in the documentation. If I try to run this test I will get :
java.lang.IllegalArgumentException: url '/bar' did not match any mappings
Where is my mistake ? Can someone help me please ?
You should run URL mappings tests as unit tests, not as integration tests. This will solve your problem.
#TestFor(FooUrlMappings)
Note that the TestFor annotation can only be used in unit tests.
My test is also in the default package in the test/integration
directory.
Move your test to the test/unit/ directory.