Can't get Nest.PropertyName to be considered for nested - elasticsearch

I have a type of entry in elastic that is made of some imbricated properties like
{
"_source":
{
"pipeline_version":1.7,
"agent":{
"hostname":"SFPWEW11616",
"id":"a1df2f4e-6dde-43fd-8af6-b3726124fdf7",
"type":"winlogbeat",
"ephemeral_id":"78be9770-dab9-4c56-a67e-b1a372a2f899",
"version":"7.5.1"
}
}, [...]
}
I'm trying to get my POCO to represent a flatten vie of this object. According to what I found in the documentation, I tried doing something in the like of
Friend Class ElasticEventLogEntry
<Nest.PropertyName("agent.hostname")>
Public Property AgentHostName As String
[...]
End Class
But no matter what I try, the value is always empty. I've seen some other posts using the NestedAttribute attribute but from what I could find, this is only useful if we want to also create nested objects in our POCO structure which isn't my case. What am I missing?

It's not possible to do what you're trying to do, at least not without writing your own JSON serialization for your ElasticEventLogEntry type and hooking up with JsonNetSerializer.
A better approach would be to model ElasticEventLogEntry differently
Public Class ElasticEventLogEntry
<DataMember(Name:="pipeline_version")>
Public Property PipelineVersion As String
Public Property Agent As Agent
End Class
Public Class Agent
Public Property Hostname As String
Public Property Id As String
Public Property Type As String
<DataMember(Name:="ephemeral_id")>
Public Property EphemeralId As String
Public Property Version As String
End Class
Then agent hostname will be deserialized to .Agent.Hostname

Related

Mapping of Dynamic fields in RestfulController POST (save) method

How do I enable RestfulController to auto-map or even manually map the dynamic fields to domain classes implementing MongoEntity? I have a domain class as below:
class Company implements MongoEntity<Company> {
String id = UUID.randomUUID().toString()
String name
String email
String phone
}
And I have a RestfulController setup for CRUD operations as below
class CompanyController extends RestfulController<Company> {
#Transactional
def save(Company company) {
if(company.hasErrors()) {
respond company.errors
}
else {
company.insert(flush:true)
respond company, status: CREATED
}
}
}
When I POST a request with some additional JSON fields, how do I get them auto-mapped to gorm_dynamic_attributes ? Currently the company object does not return any information on the dynamic attributes. Another problem I am facing is that request.JSON is also null so I cannot manually map either. Any suggestions would be highly appreciated.
I'm pretty sure, that the problem is not in data binding of your controller, but rather in persisting of the domain class instance.
I would change the domain class like so:
import grails.gorm.annotation.Entity
#Entity
class Company {
String id
String name
String email
String phone
def beforeValidate() {
if( !id ) setId UUID.randomUUID().toString()
}
static mapping = {
id generator:'assigned'
}
}
to use the assigned generator. You could put your id generation either in the controller / service code, or leave it inside the domain class' beforeValidate. In the later case pay special attention to when the id shall be generated, as beforeValidate() is called pretty often. Also note, that inside beforeValidate() a setter must be called.
I tested the similar domain class of mine with save() and insert() and in both cases that works like charm.

Spring Data MongoDB: Dynamic field name converter

How do I set the MongoDB Document field name dynamically (without using #Field)?
#Document
public class Account {
private String username;
}
For example, field names should be capitalized. Result:
{"USERNAME": "hello"}
And I want this dynamic converter to work with any document, so a solution without using generics.
This a bit strange requirement. You can make use of Mongo Listener Life cycle events docs.
#Component
public class MongoListener extends AbstractMongoEventListener<Account> {
#Override
public void onBeforeSave(BeforeSaveEvent<Account> event) {
DBObject dbObject = event.getDBObject();
String username = (String) dbObject.get("username");// get the value
dbObject.put("USERNAME", username);
dbObject.removeField("username");
// You need to go through each and every field recursively in
// dbObject and then remove the field and then add the Field you
// want(with modification)
}
}
This is a bit cluncky, but I believe there is no clean way to do this.

Spring MVC mapping #RequestBody with variables containing a dot

I am doing a POST request to my Rest Contoller with the following object:
{
"relationship.name": "someting"
}
I'd like to map that to a POJO:
public class Request {
private String relationshipName;
// Getters, setter and contructor
}
How would I dot that?
Annotate your property with #JsonProperty
public class Request {
#JsonProperty("relationship.name")
private String relationshipName;
...
}
By default, the mapping will use the variable name as the key for the property. So without the annotation, it would expect relationshipName. #JsonProperty allows you to customize the key without changing the variable name.
Have u tried using #JsonProperty on relationshipName?
#JsonProperty(name), tells Jackson ObjectMapper to map the JSON property name to the annotated Java field's name.

How can I put an instance of an object as session attribute in a Spring MVC project?

I am working on a Spring MVC application and I have the following problem.
I have this RegistrazioneInfo class that contains some information inserted into a form by the user:
public class RegistrazioneInfo {
#NotNull
#Size(min=16, max=16)
private String codiceFiscale;
String gRecaptchaResponse;
public String getCodiceFiscale() {
return codiceFiscale;
}
public void setCodiceFiscale(String codiceFiscale) {
this.codiceFiscale = codiceFiscale;
}
public String getgRecaptchaResponse() {
return gRecaptchaResponse;
}
public void setgRecaptchaResponse(String gRecaptchaResponse) {
this.gRecaptchaResponse = gRecaptchaResponse;
}
}
Then I have this controller class:
#Controller
public class RegistrazioneController extends BaseController {
private RegistrazioneInfo registrazioneInfo;
...............................................
...............................................
...............................................
}
that contains some methods handling request towards some resources.
Ok, my problem is that I want to use an instance of the previous RegistrazioneInfo class as session attribute by the use of the #SessionAttributes Spring annotation as shown here: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-sessionattrib
My problem is, in the previous example do something like this:
#SessionAttributes("pet")
public class EditPetForm {
// ...
}
So what exactly is pet? I think that it is something like an id that identify the object that have to be used as a session attribute or something like this. How can I say to put an instance of my RegistrazioneInfo as session attribute?
#SessionAttributes is declared in a Controller Class (#Controller), so on the class level.
Pet is an Bean Object that persist in HttpSession
From the documentation:
This will typically list the names of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans. Declared at the type level, applying to the model attributes that the annotated handler class operates on.
(emphasis is mine)
Also note that, as indicated in the documentation, you should not use that for "non temporary" elements.

Spring: #NestedConfigurationProperty List in #ConfigurationProperties

Hi I am trying to get the following configuration up and running.
#ConfigurationProperties(prefix="my")
public class Config {
#NestedConfigurationProperty
private List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>();
public List<ServerConfiguration> getServers() {
return this.servers;
}
}
#ConfigurationProperties(prefix = "server")
public class ServerConfiguration {
private String name;
private String description;
}
So, I want to have multiple server configs nested in objects.
I tried setting the properties with the following properties file. I can see that the list is added up by items but the members of the server are never set (name, description)
my.servers[0].name=test
my.servers[0].server.name=test
my.servers[1].name=test
my.servers[1].server.name=test
To extend what Maciej said already.
#ConfigurationProperties should be set only on root objects (that is objects that are responsible to handle a given prefix. There is no need to annotated nested objects with it.
#NestedConfigurationProperty is only used by the meta-data generator (to indicate that a property is not a single value but something we should explore to generate additional meta-data. In the case of the List there isn't any finite amount of properties so the meta-data will have to stop at the list.
In any case you need a getter and a setter for each singular property. We don't do field binding and we require a public getter to avoid exposing unnecessary properties in the meta-data.
You need to add setters and getters to ServerConfiguration
You don't need to annotate class with nested properties with #ConfigurationProperties
There is a mismatch in names between ServerConfiguration.description and property my.servers[X].server.name=test

Resources