I have a harcoded value in one of my controller
public regions = ['code1','code2']
Now have to read these values from config.groovy file,
I tried to define in config.groovy:-
region = "code1,code2"
in mycontroller :-
def aws = grailsApplication.config.awsRegions;
public awsRegions = aws.split(",")
But it didn't work.
In the Config.groovy you can do:
awsRegions = ['Region 1', 'Region 2']
Then in your Controller you can do:
def awsRegions = grailsApplication.config.awsRegions
Your changes are not working in the comments with Sathish Kumar because you are calling your property "awsRegion" in Config.groovy and accessing it with "grailsApplicatio.config.awsRegions". The keys must match.
1
public regions = ['code1','code2']
should that not be
public List regions = ['code1','code2']
or
public List<String> regions = ['code1','code2']
In the world of groovy / grails public is not required so long as it is not a static variable
2
def aws = grailsApplication.config.awsRegions;
public awsRegions = aws.split(",")
When in doubt :
def aws = grailsApplication.config.awsRegions;
println "aws is ${aws} object class is ${aws.getClass()}"
You should find the println returns [element,e2,e3] within a List already. The getClass() of something tells you what it actually is so you should find it is already a list and does not require the additional split which you would do on a flat string
Related
My requirement is to create a list of values inside application.properties file.
com.mail = aaaa, bbbb, cccc
I want to retrieve these values in my controller class and iterator over each value and should check with the requestbody/queryparam values which gets, when hitting an API
Consider I have an API
#RestController
#RequestMapping("/response")
public class HomeController {
#PostMapping("/postbody")
public String postBody(#RequestBody String fullName) {
//here I have to validate the fullName with the list I created in the application.properties
Eg: if(fullname.equals(aaaa) or if(fullname.equals(bbbb) or if(fullname.equals(cccc)
// I want to iterator over the list to check any value is matching with fullName.
}}
How to declare list of values inside application.properties? How to retrieve that list inside controller class? Post retrieving how to iterate over the list to check whether it matches with requestbody/queryparam value?
Please provide me with solution. Thank you
Split the list using a comma as the delimiter.
private String[] mailList;
public HomeController( #Value("${com.mail}") final String mail) {
mailList = mail.split(",")
}
You can now use mailList inside postBody method.
use comma separated values in application.properties
com.mail = aaaa, bbbb, cccc
Java code for access
#Value("${com.email}")
String[] mailList;
It worked.
In Application. properties you will add the parameter with values separated with ','
com.mail = aaaa,bbbb,cccc
in the controller will get the Values
#Value("${com.mail}")
private List<String> mailListValues;
#RestController
#RequestMapping("/response")
public class HomeController {
#Value("${com.mail}")
private List<Object> mailListValues;
#PostMapping("/postbody")
public String postBody(#RequestBody String fullName) {
if(!mailListValues.isEmpty()){
long countOfMatch = mailListValues.stream()
.filter(item->item.equals(fullName)).count();
if(countOfMatch >0)
// your Business .....
}
}}
please check images
In SDN+OGM I used the following method to extend the base repository with additional functionality, specifically I want a way to find or create entities of different types (labels):
#NoRepositoryBean
public class MyBaseRepository<T> extends SimpleNeo4jRepository<T, String> {
private final Class<T> domainClass;
private final Session session;
public SpacBaseRepository(Class<T> domainClass, Session session) {
super(domainClass, session);
this.domainClass = domainClass;
this.session = session;
}
#Transactional
public T findOrCreateByName(String name) {
HashMap<String, String> params = new HashMap<>();
params.put("name", name);
params.put("uuid", UUID.randomUUID().toString());
// we do not use queryForObject in case of broken data with non-unique names
return this.session.query(
domainClass,
String.format("MERGE (x:%s {name:$name}) " +
"ON CREATE SET x.creationDate = timestamp(), x.uuid = $uuid " +
"RETURN x", domainClass.getSimpleName()),
params
).iterator().next();
}
}
This makes it so that I can simply add findOrCreateByName to any of my repository interfaces without the need to duplicate a query annotation.
I know that SDN 6 supports the automatic creation of a UUID very nicely through #GeneratedValue(UUIDStringGenerator.class) but I also want to add the creation date in a generic way. The method above allows to do that in OGM but in SDN the API changed and I am a bit lost.
Well, sometimes it helps to write down things. I figured out that the API did not change that much. Basically the Session is replaced with Neo4jOperations and the Class is replaced with Neo4jEntityInformation.
But even more important is that SDN 6 has #CreatedDate which makes my entire custom code redundant.
A simplified version. I have two classes:
Public Class mSystem
Public Property ID as ObjectID
Public Property Name as string
End Class
Public Class mEmulator
Public Property ID as ObjectID
Public Property Name as string
<BsonRef("mSystems")>
Public Property AssociatedSystems as New List(Of mSystem)
End Class
Public Class Main
Public Sub EmaultorsLinkedToSystem
dim SelectedSystem as mSystem = db.Collections.mSystems.Find(Function(x) x.Name = "Sony Playstation").FirstOrDefault
test = db.Collections.mEmulators.Include(Function(x) x.AssociatedSystems).Find(Function(y) y.AssociatedSystems.Contains(SelectedSystem)).ToList
End sub
End Class
Now I know one mEmulator data object has "Sony Playstation" in its List(of mSystem). However, test returns null. Why isn't this finding it? I've tried a few permutations, but cant get this to work. Any ideas?
The Include method is used for resolving references to other collections, and you're not using BsonRef with AssociatedSystems (at least not in this example you provided). In your example, the instances of mSystem in AssociatedSystems are not being stored in a separate collection, but as an array of embedded documents in the emulators collection.
Try removing the Include call, it should work fine.
I've got a set of domain and controller classes called: Organization and OrganizationController respectively.
THe OrganizationController only has one method:
def index() {
def organizations = Organization.list()
[orgs: organizations]
}
I've tried to mock out the Domain class by 2 ways.
The first way was using the #Mock annotation, and creating the objects and saving:
void "test index"() {
given:
new Organization(name: 'JIMJIM').save()
new Organization(name: 'ABC').save()
def expected = [org: [new Organization(name: 'JIMJIM'),
new Organization(name: 'ABC')]]
when:
def actual = controller.index()
then:
actual == expected
}
That caused Oraganization.list to return an empty list. Actual returns [org: []]
I also tried using mockDomain:
void "test index"() {
given:
mockDomain(Organization, [new Organization(name: 'JIMJIM'),
new Organization(name: 'ABC')
])
def expected = [org: [new Organization(name: 'JIMJIM'),
new Organization(name: 'ABC')]]
when:
def actual = controller.index()
then:
actual == expected
}
However I still got the same result. Why is it that my domain classes are not getting mocked?
My test decoration (OrganizationControllerSpec) is the following:
#TestFor(OrganizationController)
#Mock(Organization)
#TestMixin(DomainClassUnitTestMixin)
class OrganizationControllerSpec extends Specification {
I'm using Grails 2.3.8.
The first snippet seems to be ok, but...
First of all, were the Organization objects actually created? Are all required fields provided? Please, try using save(failOnError: true) to make sure.
Moreover, in controller you have orgs, while you use org in the test. Is it only a misspell?
Also, unless you have equals method overwritten in Organization class, the objects from database are not equal to the ones you create with new operator.
Grails 2.2.0
How do I access the custom configuration variables in a Grails domain object constraints.
I would like to have something like this:
class User {
def grailsApplication
String name
static constraints = {
name size: grailsApplication.config.maxlength
}
}
But it fails with "No such property: grailsApplication". I have tried to get it work by following suggestions in getting grails 2.0.0M1 config info in domain object, and static scope? but have not managed to get any combination to work.
How do I access config in domain object constraints? In addition how do I handle such a case in a unit test for the domain constraints?
You can use the grails.util.Holders class to get access to the configuration object as follows:
In Config.groovy:
myMaxSize = 10
In your domain class:
class User {
String name
static constraints = {
name minSize: Holders.config.myMaxSize
}
}