How Can I flatten my DTO into VO - dozer

Here is a sample simple scenario that I want to map. I have a DTO as follows
Class Person {
String Name;
List<Contact> contacts;
}
Class Contact {
String type; //values 'home', 'work', 'mobile' etc
Phone number;
}
Class Phone {
String areaCode;
String number;
}
I need to map it to a VO object as follows
Class PersonVO {
String Name;
PhoneVO homePhone;
PhoneVO workPhone;
}
Class PhoneVO {
String areaCode;
String number;
}
Is there an easier way to map them using dozer or I have to use customconvertors? how can I use default mapping for phone to phoneVO?

You cannot map Person DTO and PersonVO without using a CustomConverter,
because Person's Phone 'number' variable gets it's value based on whether
'type' variable contains values 'home' or 'work', and so on. Dozer cannot handle such
conditional cases.
However, default mapping for Phone and PhoneVO alone is very simple:
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mapping>
<class-a>{package-name}.Phone</class-a>
<class-b>{package-name}.PhoneVO</class-b>
</mapping>
</mappings>

Related

mapstruct - map object with nested list to flat list

I cannot manage a problem that seems to be trivial.
I just want to map relation to flat table.
class Train {
Integer trainNumber;
List<Station> stations;
}
class Station {
String name;
String coords;
}
I want to map this classes to flatten one
class TrainStation {
Integer trainNumber;
String stationName;
}
How to do this with mapstruct?

how to make a public property even with underscore in dart?

I'm fetching some json data from a rest api server and one of its keys is _id and I need to serialize this json to a dart object using built_value, but this isn't allowed because in dart _id is private and built_value doesn't allow me to define a private getter in my model!
So what do I do?
package:built_value has a mechanism to rename fields. As mentioned in its README.md:
The corresponding dart class employing built_value might look like this. Note that it is using ... the #BuiltValueField annotation to map between the property name on the response and the name of the member variable in the Person class.
...
#nullable
#BuiltValueField(wireName: 'first_name')
String get firstName;
So in your case, you should be able to do something like:
#BuiltValueField(wireName: '_id')
String get id;
You can replace '_id' with 'id' once you got JSON Response String. Then serialize it.
Model Class :
#JsonSerializable(explicitToJson: true)
class PersonModel{
int id;
String name;
PersonModel(this.id,this.name);
factory PersonModel.fromJson(Map<String, dynamic> json) => _$PersonModel FromJson(json);
Map<String, dynamic> toJson() => _$PersonModelToJson(this);
}
Replace :
String responseString = response.body
String newResponseString = responseString.replaceAll('_id', 'id');
PersonModel personModel = PersonModel.fromJson(jsonDecode(newResponseString));
Now you can use personModel.id to access _id in frontend.

Why does dart has got special keywords for get and set?

I am new to flutter, I was just wondering special keywords for getter and setter. Why has dart kept special keywords get and set for getter and setter respectively? Is there any particular reason, because like other languages it could have been done with simple functions also.
Example in dart we have get and set keywords.
class Person {
String _name;
String get name => _name;
set name (String val) => _name = val;
}
In java, we do the same using public methods.
// Java, No get, set keywords used
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Why do we need separate get and set keywords in dart? Is that different from a normal getter and setter methods that we use in java, cop
We could simply use
class Person {
String _name;
String getName() => _name;
void setName(String val) => _name=val;
}
I know this is something like using variables directly instead of methods, Simply my question is Is there anything that we can't achieve in a simple getter and setter methods that we can do using get and set keywords?
This is basically for convenience and backward compatibility. Let's say you start off with a public field:
class Person {
final String name;
}
but then you decide name should rather be a calculated field based on first and last name:
class Person {
final String lastName;
final String firstName;
String get name => '$firstName $lastName';
}
in java it is a best practice to never, ever have a public class member variable, just because it doesn't have a way to transition to a method without changing the API. so you ALWAYS have to write getVariable() acessor methods, even if 99% of those only have return variable; as body.

Sorting strings based on the integer value they represent in hibernate search

I have an entity with a string field in it.
Sometimes this string field stores actual words, so sorting based on lexicographical order makes sense. However, there is a use case where this field stores string values like "0%", "10%", "100%", "20%".
The default string sorting generates the following sequence: 0% 10% 100% 20%.
The ideal sequence after sorting would be 0%, 10%, 20%, 100%(determined by the percentage they represent).
It is guaranteed that there is no mixed data, i.e, you won't have "10%" and "word" appear in the same sequence that needs to be sorted.
My question is if there is a way to achieve the string sorting based on the numerical value they represent?
Ideally, you should alter your model to have two fields: one of integer type where you'll hold the percentage, and one of string type where you will hold the string value:
#Entity
#Indexed
public class MyEntity {
#Field
#SortableField
private int percentage;
#Field
#SortableField
private String notPercentage;
// ... other properties, getters and setters ...
}
Then when sorting you'll just sort on both fields. Since you are certain they are mutually exclusive, it's not a problem to sort on both:
QueryBuilder queryBuilder = ...;
FullTextQuery ftQuery = ...;
ftQuery.sort(queryBuilder.sort().byField("percentage").andByField("notPercentage").createSort());
Alternatively, if you really want to keep a single String property in your ORM model (to each his own...), you can use a custom bridge to apply padding to your values, so that they are sorted correctly:
#Entity
#Indexed
public class MyEntity {
#Field(bridge = #FieldBridge(impl = PaddingIfPercentageBridge.class))
#SortableField
private String percentageOrNot;
// ... other properties, getters and setters ...
}
public class PaddingIfPercentageBridge implements TwoWayStringBridge {
private static final Pattern PERCENTAGE = Pattern.compile("[0-9]+%");
#Override
public String objectToString(Object object) {
if ( object == null ) {
return null;
}
String string = (String) object;
if ( !PERCENTAGE.matcher( string ).matches() ) {
return string;
}
StringBuilder paddedPercentage = new StringBuilder();
for ( int padIndex = string.length(); padIndex < 4; padIndex++ ) {
paddedPercentage.append( '0' );
}
return paddedPercentage.append( string ).toString();
}
#Override
public Object stringToObject(String stringValue) {
// Ideally you should remove the padding here...
return stringValue;
}
}
Then you can sort on a single field:
QueryBuilder queryBuilder = ...;
FullTextQuery ftQuery = ...;
ftQuery.sort(queryBuilder.sort().byField("percentageOrNot").createSort());

Wicket - DropDownChoice from Enum to Primitive

Im having some problem with DropDownChoice.
I have an Enum with a list of school title like:
public enum StudyTitle {
NONE(null,null),ELEMENTARY("1","Elementary"),COLLEGE("2","College");
private String code;
private String description;
private StudyTitle(String code, String description){
setCode(code);
setDescription(description);
}
[setter and getter]
}
Then I have a Pojo with a String proprerty call "studyTitleCode" where I want to put the code (ex 1 for elementary, 2 for college etc...).
When I create a DropDownChoice Wicket doesn't allow me to have a proprerty Model of type String if the DropDownChoice is of type StudyTitle.
Ex.
[building the listOfStudyTitle as ArrayList of Enums]
DropDownChoice<String> studyLevel = new DropDownChoice<String>("id",new PropertyModel<String>(myPojo,"studyTitleCode"),listOfStudyTitle,new ChoiceRenderer<StudyTitle>("description","code"));
Is there a Method to allow Wicket to link one property of the Enum to the Property of Model?
Thanks
The choice options for an AbstractSingleSelectChoice must match the type of the value model. The only related config option for the DropDownChoice that I'm aware of is the IChoiceRenderer which allows you to set how the enum value is rendered (vs the default call toString()).
One option would be, instead of using the enum instance itself for your choices model, give the enum a String property that can be used:
public enum TestEnum {
ONE ("ONE"),
TWO ("TWO"),
THREE ("THREE");
private String value;
TestEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static List<String> getStringValues()
{
List<String> stringValues = new ArrayList<String>();
for (TestEnum test : values()) {
stringValues.add(test.getValue());
}
return stringValues;
}
}
#Override
protected void onInitialize() {
super.onInitialize();
IModel<String> myStringValueModel = new Model<String>();
add(new DropDownChoice<String>("id", myStringValueModel, TestEnum.getStringValues()));
}