Get list of instances, Grails - grails

I need to get list of instances. I did so to do this:
def availableCafee = Cafee.list()
But now, my task is complicated. It requires if certain field in instance doesn't have an empty string value, other fields of the instance must be found via some controller and the other instance by this string value. Domain class is below.
If apiInit is empty, the instance added to list how in example above, if apiInit isn't empty, it assumed other fields wasn't initialized, so getting other fields requires via controller, which I've done and the other instance.So external API work is emulate. How to change example above to do this?
class Cafee {
String cafeeName = ""
int totalReservationPlaces = 0
double placeCost = 0
String currencyType = ""
boolean isReservationAvailable = false
boolean reservationTimeLimit = false
boolean reservationDateLimit = false
int totalPlaces = 0
LocalTime startTimeLimit = new LocalTime()
LocalTime endTimeLimit = new LocalTime()
Date startDateLimit = new Date()
Date endDateLimit = new Date()
String region = ""
String city = ""
String apiInit = ""
}

I think what you are trying to say is that a nullable object is causing the object not to be saved.
The solution is quite simple:
static constraints = {
apiInit nullable: true
}
Have a read here: rejected-value-null
So ideally set all those objects that are could be nullable should be set
ChatUser.groovy
you can also set the defaultValue of an object in the mapping:
MailingListBase.groovy
Please note if it is an already generated Database table any attempt now to set to nullable after it has been previously created will not work. you will either have to set this manually or drop it and let it regenerate..

Related

How to Serialize an Object to Json in F# excluding defaults and Keeping Enum Names

I thought this would have been easy but I am having issues ticking all the boxes that I need in this.
I need to
Serialize an object to Json
Ignore any properties not set
Use the ENum names instead of integer values
I have generated all the models for this using the Open API Generator based on a .yaml spec.
My first attempt was to get a bit of code from what looks like an old serializer
let json<'t> (myObj:'t) =
use ms = new MemoryStream()
let serialiser: DataContractJsonSerializer = new DataContractJsonSerializer(typeof<'t>)
let settings: DataContractJsonSerializerSettings = new DataContractJsonSerializerSettings()
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
Encoding.Default.GetString(ms.ToArray())
This function actually does everything fine - except it copiess the enum numbers instead of names and I can't see an option to make this happpen.
My other attempt is using System.Text.Json.JsonSerializer:
let options
= new JsonSerializerOptions(
)
options.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingDefault
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase))
let jsonString:string = JsonSerializer.Serialize(shipmentRequest, options)
I have tried a few different things ( including excluding the Enum converter ) and I always get the following error.
Unable to cast object of type 'System.Int32' to type
'System.Nullable`1[Zimpla.Model.ExpressPackageReference+TypeCodeEnum]'
The specific Object ( roughly ) that it is having an issue with is:
[DataContract(Name = "ExpressPackageReference")]
public partial class ExpressPackageReference : IEquatable<ExpressPackageReference>, IValidatableObject
{
......etc
[DataMember(Name = "typeCode", EmitDefaultValue = false)]
public TypeCodeEnum? typeCode
{
get{ return _typeCode;}
set
{
_typeCode = value;
_flagtypeCode = true;
}
}
This particular property is not even set so it should be skipping over it theoretically. It is possible that I am not generating the object correctly
Without understanding all the details here, I think you are asking how you can serialize an object to json while omitting all properties that are null using System.Text.Json.
To accomplish that you have to set the following option:
options.IgnoreNullValues <- true
Here are the docs for this option:
https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.ignorenullvalues?view=net-5.0#System_Text_Json_JsonSerializerOptions_IgnoreNullValues

Modify property inside of a behaviourRelay array in RxSwift

I have an array defined using RxSwift as
public var calendarNDays = BehaviorRelay<[CalendarControlDayModel]>(value: [])
CalendarControlDayModel is a structure as below.
struct CalendarControlDayModel {
var date: String = ""
var day: Int = 0
var name: String = ""
}
Once the calendarNDays is updated with elements at some point of time I want to modify the name property of i-th element in the array.
Like self.calendarNDays.value[i].name = "Nancy". However, I get the compilation error "Cannot assign to property: 'value' is a get-only property".
What is the way to modify a particular property of an element in a behaviour relay array?
As the compiler suggests the value in BehaviorRelay is a read-only property.
Therefore in order to make changes to the array you first need to copy it and use the accept method to reflect the changes.
Similar to
var update = calendarNDays.value
update[i].name = “Nancy”
calendarNDays.accept(update)

java.lang.NullPointerException in command object

I want to parse a string to date just before validate a command object, here is my command object code
class ActivitiesCommand {
List schools
List departments
Date from
Date to
static constraints = {
schools nullable:false
departments nullable:false
from blank:false
to blank:false
}
def beforeValidate() {
def from = new Date().parse("yyyy-MM-dd", from)
def to = new Date().parse("yyyy-MM-dd", to)
}
}
but i am getting java.lang.NullPointerException when i try def from = new Date().parse("yyyy-MM-dd", from) or def to = new Date().parse("yyyy-MM-dd", to). What can i do in order to successfully parse the date before validate command object?
I read the command object docs. I got this sample from there. I tried if removing ? beforeValidate does not work, so i understand i need to provide a null safe but i do not know how to do it in my scenario
class Person {
String name
static constraints = { name size: 5..45 }
def beforeValidate() { name = name?.trim() }
}
Thanks for your time.
from and to is set to Date in the Command Object, so request parameter string with from and to names will be converted to a Date and then bound to these field.
If the expected date format matches then binding will be successful.
In your case, from and to in beforeValidate is treated as String instead. If they are String actually then you can make them nullable: false in constraints or do the check as below in beforeValidate:
from = from ? Date.parse("yyyy-MM-dd", from) : new Date() - 1 //for example
Note the appropriate use of Date.parse()

Groovy Dynamic Object - How to properly reset properties?

Based on this question I created a Groovy class that will have dynamic properties.
class MyDynamic {
def propertyMissing( String name, value ) {
this.metaClass."$name" = value
value
}
}
So far all good, now I can set some non-existent property with success
MyDynamic dyna = new MyDynamic()
dyna.someProp = new Date()
My problem begins when I have another instance with the same name of property, but with another type
MyDynamic dyna2 = new MyDynamic()
dyna2.someProp = "0" //GroovyCastException: Cannot cast object '0' with class 'java.lang.String' to class 'java.util.Date'
Actually I need this because I'm creating objects with the result of a query without knowing the table and the column. I get the name of the column with the ResultSetMetaData and add the property to the instance of the dynamic object. Later I will use this object to export all the properties and values. In different tables I have the same column name, but with different types.
So my question is: how can I reset this metaClass when I'm done with the instance to not conflict with other instance?
Why not a Expando, a Map or a simple container:
class Dynamic {
def properties = [:]
void setProperty( String name, value ) {
properties[name] = value
}
def getProperty(String property) { properties[property] }
}
d = new Dynamic()
d.name = "yeah"
assert d.name.class == String
d.name = new Date()
assert d.name.class == Date

Assigning default values if NULL

I have an MVC app where a user can select company benfits, there are 10 different benefits and they can have none up to all 10 of these. In my view I have the ten listed with radio buttons to indicate whether they are required or not. There is also a calculation performed in the controller that adds all the values together to give a total.
As an example in my controller -
newuser.LifeAssurance.LifeAssuranceRequired = viewModel.LifeAssuranceRequired;
newuser.LifeAssurance.LifeAssuranceSchemeName = viewModel.LifeAssuranceSchemeName;
newuser.LifeAssurance.LifeAssuranceProviderName = viewModel.LifeAssuranceProviderName;
newuser.LifeAssurance.LifeAssuranceBenefitLevel = viewModel.LifeAssuranceBenefitLevel;
newuser.LifeAssurance.LifeAssuranceEmployerCost = viewModel.LifeAssuranceEmployerCost;
newuser.LifeAssurance.LifeAssuranceEmployeeCost = viewModel.LifeAssuranceEmployeeCost;
Since the user may decide not to choose this benefit is it possible to assign the cost as 0 if they have not made a selection in the view model? Can I check if it's null and add 0 in that case?
You can use the ?? operator (see here)
use it like this:
string someString = null;
string someOtherString = someString ?? "0";
if someString(or any other object) is not null use it, else use whatever is on the right of the ?? operator.
Maybe set your values as nullable by add ? to type, and then you can check it is null by:
var someValue = (nullableValue.HasValue) ? nullableValue.Value : 0;

Resources