Instruct orika when should map - orika

Is there a way to specifically tell Orika when to map a given item? For example I want Orika to map my items only if A.getLastModifiedTime() > B.getLastModifiedTime. Is there a way to configure this somehow?

This should do the trick:
mapperFactory.classMap(A.class, B.class)
.customize(new CustomMapper<A,B>() {
if(A.getLastModifiedTime() > B.getLastModifiedTime()){
A.getLastModifiedTime() == B.getLastModifiedTime();
}
}).register();

You can use Orika filters in order to map or not a field depending on a runtime condition. The easiest way is by means of extending Orika's NullFilter.
class MyFilter<A,B> extends NullFilter<A,B> {
private myCondition(S source, D dest) {
...
}
public <S extends A, D extends B> boolean shouldMap(final Type<S> sourceType, final String sourceName, final S source, final Type<D> destType, final String destName,
final MappingContext mappingContext) {
if (destName.equals("lastModifiedTime") && myCondition(source, dest)) {
return false;
}
return true;
}
}

Related

Spring Cloud Sleuth: Initialise baggage item

I already have this Java Configuration:
#Configuration
public class FAPIAutoConfiguration {
private static final String INTERACTION_ID = "x-fapi-interaction-id";
private final BaggageField fapiBaggageField = BaggageField.create(INTERACTION_ID);
#Bean
BaggagePropagationCustomizer baggagePropagationCustomizer() {
return builder -> builder.add(SingleBaggageField.
remote(fapiBaggageField));
}
#Bean
CorrelationScopeCustomizer correlationScopeCustomizer() {
return builder -> builder.add(SingleCorrelationField.create(fapiBaggageField));
}
}
And the propagation in a Webflux application works, but I would like to know what is the best way to initialize the baggage if it is not present in the request headers. I mean, if the header is missing, generate a value and propagate this one.
I ended up adding a TracingCustomizer to the above configuration to fill the value when is missing in that context.
#Bean
TracingCustomizer tracingCustomizer(UniqueIdGenerator generator) {
return builder -> builder.addSpanHandler(new SpanHandler() {
#Override
public boolean begin(TraceContext context, MutableSpan span, TraceContext parent) {
var value = fapiBaggageField.getValue(context);
if (value == null) {
fapiBaggageField.updateValue(context, generator.next());
}
return super.begin(context, span, parent);
}
});
}
I do not know if this is the best option yet

HTTP end point property string starts with "is" will get omit [duplicate]

This might be a duplicate. But I cannot find a solution to my Problem.
I have a class
public class MyResponse implements Serializable {
private boolean isSuccess;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Getters and setters are generated by Eclipse.
In another class, I set the value to true, and write it as a JSON string.
System.out.println(new ObjectMapper().writeValueAsString(myResponse));
In JSON, the key is coming as {"success": true}.
I want the key as isSuccess itself. Is Jackson using the setter method while serializing? How do I make the key the field name itself?
This is a slightly late answer, but may be useful for anyone else coming to this page.
A simple solution to changing the name that Jackson will use for when serializing to JSON is to use the #JsonProperty annotation, so your example would become:
public class MyResponse implements Serializable {
private boolean isSuccess;
#JsonProperty(value="isSuccess")
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
This would then be serialised to JSON as {"isSuccess":true}, but has the advantage of not having to modify your getter method name.
Note that in this case you could also write the annotation as #JsonProperty("isSuccess") as it only has the single value element
I recently ran into this issue and this is what I found. Jackson will inspect any class that you pass to it for getters and setters, and use those methods for serialization and deserialization. What follows "get", "is" and "set" in those methods will be used as the key for the JSON field ("isValid" for getIsValid and setIsValid).
public class JacksonExample {
private boolean isValid = false;
public boolean getIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
}
Similarly "isSuccess" will become "success", unless renamed to "isIsSuccess" or "getIsSuccess"
Read more here: http://www.citrine.io/blog/2015/5/20/jackson-json-processor
Using both annotations below, forces the output JSON to include is_xxx:
#get:JsonProperty("is_something")
#param:JsonProperty("is_something")
When you are using Kotlin and data classes:
data class Dto(
#get:JsonProperty("isSuccess") val isSuccess: Boolean
)
You might need to add #param:JsonProperty("isSuccess") if you are going to deserialize JSON as well.
EDIT: If you are using swagger-annotations to generate documentation, the property will be marked as readOnly when using #get:JsonProperty. In order to solve this, you can do:
#JsonAutoDetect(isGetterVisibility = JsonAutoDetect.Visibility.NONE)
data class Dto(
#field:JsonProperty(value = "isSuccess") val isSuccess: Boolean
)
You can configure your ObjectMapper as follows:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
&& method.getName().startsWith("is")) {
return method.getName();
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
I didn't want to mess with some custom naming strategies, nor re-creating some accessors.
The less code, the happier I am.
This did the trick for us :
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonIgnoreProperties({"success", "deleted"}) // <- Prevents serialization duplicates
public class MyResponse {
private String id;
private #JsonProperty("isSuccess") boolean isSuccess; // <- Forces field name
private #JsonProperty("isDeleted") boolean isDeleted;
}
Building upon Utkarsh's answer..
Getter names minus get/is is used as the JSON name.
public class Example{
private String radcliffe;
public getHarryPotter(){
return radcliffe;
}
}
is stored as { "harryPotter" : "whateverYouGaveHere" }
For Deserialization, Jackson checks against both the setter and the field name.
For the Json String { "word1" : "example" }, both the below are valid.
public class Example{
private String word1;
public setword2( String pqr){
this.word1 = pqr;
}
}
public class Example2{
private String word2;
public setWord1(String pqr){
this.word2 = pqr ;
}
}
A more interesting question is which order Jackson considers for deserialization. If i try to deserialize { "word1" : "myName" } with
public class Example3{
private String word1;
private String word2;
public setWord1( String parameter){
this.word2 = parameter ;
}
}
I did not test the above case, but it would be interesting to see the values of word1 & word2 ...
Note: I used drastically different names to emphasize which fields are required to be same.
You can change primitive boolean to java.lang.Boolean (+ use #JsonPropery)
#JsonProperty("isA")
private Boolean isA = false;
public Boolean getA() {
return this.isA;
}
public void setA(Boolean a) {
this.isA = a;
}
Worked excellent for me.
If you are interested in handling 3rd party classes not under your control (like #edmundpie mentioned in a comment) then you add Mixin classes to your ObjectMapper where the property/field names should match the ones from your 3rd party class:
public class MyStack32270422 {
public static void main(String[] args) {
ObjectMapper om3rdParty = new ObjectMapper();
om3rdParty .addMixIn(My3rdPartyResponse.class, MixinMyResponse.class);
// add further mixins if required
String jsonString = om3rdParty.writeValueAsString(new My3rdPartyResponse());
System.out.println(jsonString);
}
}
class MixinMyResponse {
// add all jackson annotations here you want to be used when handling My3rdPartyResponse classes
#JsonProperty("isSuccess")
private boolean isSuccess;
}
class My3rdPartyResponse{
private boolean isSuccess = true;
// getter and setter here if desired
}
Basically you add all your Jackson annotations to your Mixin classes as if you would own the class. In my opinion quite a nice solution as you don't have to mess around with checking method names starting with "is.." and so on.
there is another method for this problem.
just define a new sub-class extends PropertyNamingStrategy and pass it to ObjectMapper instance.
here is a code snippet may be help more:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
String input = defaultName;
if(method.getName().startsWith("is")){
input = method.getName();
}
//copy from LowerCaseWithUnderscoresStrategy
if (input == null) return input; // garbage in, garbage out
int length = input.length();
StringBuilder result = new StringBuilder(length * 2);
int resultLength = 0;
boolean wasPrevTranslated = false;
for (int i = 0; i < length; i++)
{
char c = input.charAt(i);
if (i > 0 || c != '_') // skip first starting underscore
{
if (Character.isUpperCase(c))
{
if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '_')
{
result.append('_');
resultLength++;
}
c = Character.toLowerCase(c);
wasPrevTranslated = true;
}
else
{
wasPrevTranslated = false;
}
result.append(c);
resultLength++;
}
}
return resultLength > 0 ? result.toString() : input;
}
});
The accepted answer won't work for my case.
In my case, the class is not owned by me. The problematic class comes from 3rd party dependencies, so I can't just add #JsonProperty annotation in it.
To solve it, inspired by #burak answer above, I created a custom PropertyNamingStrategy as follow:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if (method.getParameterCount() == 1 &&
(method.getRawParameterType(0) == Boolean.class || method.getRawParameterType(0) == boolean.class) &&
method.getName().startsWith("set")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = "is" + method.getName().substring(3);
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
// do nothing and fall through
}
}
return super.nameForSetterMethod(config, method, defaultName);
}
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
&& method.getName().startsWith("is")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = method.getName();
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
// do nothing and fall through
}
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
Basically what this does is, before serializing and deserializing, it checks in the target/source class which property name is present in the class, whether it is isEnabled or enabled property.
Based on that, the mapper will serialize and deserialize to the property name that is exist.

How in razor core to create a link that has all current parameters plus some more

I'm on a page SomePage?A=a&B=b&...
I want to construct a URL that has all of the current GET parameters plus some more from an IDictionary<string, string> that I have.
The tag helper asp-all-route-data="#myDictionary" will get set the parameters from my dictionary, but I don't understand:
how to create a link with all of the current parameters; or
how to add extra parameters to such a link.
Well this works, but I think it's a bit crap because:
this feels like a really obvious thing to want to so so I don't believe that there isn't an out of the box way to do it,
I can't get the extension method to work -- it has to be called as MakeGet(this, d) rather than just MakeGet(d), and
Shouldn't we be using something like a NameValueCollection that models multiple keys as are supported in GET?
public static IDictionary<string, string> MakeGet<T>(this RazorPage p, IDictionary<string, T> d)
{
return MakeGet(p, d.ToDictionary(z => z.Key, z => { try { return z.ToString(); } catch { return null; } }));
}
public static IDictionary<string, string> MakeGet(this RazorPage p, IDictionary<string, string> d)
{
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (string k in d.Keys)
{
if (!string.IsNullOrWhiteSpace(d[k]))
{
result.Add(k, d[k]);
}
}
IQueryCollection get = p.ViewContext.HttpContext.Request.Query;
foreach (KeyValuePair<string, StringValues> q in p.ViewContext.HttpContext.Request.Query)
{
if (!result.Keys.Contains(q.Key))
{
result.Add(q.Key, string.Join(",", q.Value));
}
}
return result;
}
The next problem is how to subsequently remove a parameter in the controller in order to do a redirect.
public async Task<IActionResult> OnGetTableDeleteAsync()
{
// Need to remove parameter LineNumber.
return RedirectToAction("Get");
}
Well this is what I've come up with for the parameter removal.
public static RouteValueDictionary QueryWithout(this PageModel p, params string[] remove)
{
RouteValueDictionary q = new RouteValueDictionary();
foreach (var kv in (QueryHelpers.ParseQuery(p.Request.QueryString.Value).Where(z => !remove.Contains(z.Key))))
{
q.Add(kv.Key, kv.Value);
}
return q;
}
Being used like this
public async Task<IActionResult> OnGetTableDeleteAsync(int lineNumber)
{
ImportStagingRecord i = _context.ImportStagingRecords.Find(FileId, lineNumber);
if( i != null)
{
_context.ImportStagingRecords.Remove(i);
await _context.SaveChangesAsync();
}
Microsoft.AspNetCore.Routing.RouteValueDictionary q = BaseUri.QueryWithout(this, "LineNumber", "handler");
return RedirectToAction("", q);
}
Again, I think it's crap.
(The query string contains lots of parameters for sorting, filtering, and paging the table of ImportStagingRecords which need to be preserved across requests.)

ArrayList partial integrating one List in another

I have a function that creates regular Objects of a same type and I cannot avoid that step.
When I use List.addAll(*) I will get many "Duplications" that are not equal in sense of Objectivity.
I have a very bad coded solution and want to ask if there could be a better or more effective one maybe with Java-Util-functions and defining a Comparator for that single intermezzo?
Here is my bad smell:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
if(allnewWiki.isEmpty())
allnewWiki.addAll(newWiki);
else{
for(SeMo_WikiArticle nn : newWiki){
boolean allreadyIn = false;
for(SeMo_WikiArticle oo : allnewWiki){
if(nn.getID()==oo.getID())
allreadyIn= true;
}
if(!allreadyIn)
allnewWiki.add(nn);
}
}
}
Any Ideas?
Add an override function of equals() into class SeMo_WikiArticle :
class SeMo_WikiArticle {
// assuming this class has two properties below
int id;
String name;
SeMo_WikiArticle(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public boolean equals(Object obj) {
// implement your own comparison policy
// here is an example
if (obj instanceof SeMo_WikiArticle) {
SeMo_WikiArticle sw = (SeMo_WikiArticle)obj;
if (this.id == sw.id && (this.name == sw.name || this.name.equals(sw.name))) {
return true;
}
}
return false;
}
}
After that you can use contains() to judge if the list has already contains the specific object of SeMo_WikiArticle.
Here is the code:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
for (SeMo_WikiArticle sw : newWiki) {
if (!allnewWiki.contains(sw)) {
allnewWiki.add(sw);
}
}
}

Jackson : Conditional select the fields

I have a scenario where i need to use the payload as
{"authType":"PDS"}
or
{"authType":"xyz","authType2":"abc",}
or
{"authType":"xyz","authType2":"abc","authType3":"123"}
or
any combination except for null values.
referring to the code i have 3 fields but only not null value fields be used.
Basically i don't want to include the field which has null value.
Are there any annotations to be used to get it done
public class AuthJSONRequest {
private String authType;
private String authType2;
private String authType3;
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getAuthType2() {
return authType2;
}
public void setAuthType2(String authType2) {
this.authType2 = authType2;
}
public String getAuthType3() {
return authType3;
}
public void setAuthType3(String authType3) {
this.authType3 = authType3;
}
}
Try JSON Views? See this or this. Or for more filtering features, see this blog entry (Json Filters for example).
This is exactly what the annotation #JsonInclude in Jackson2 and #JsonSerialize in Jackson are meant for.
If you want a property to show up only when it is not equal to null, add #JsonInclude(Include.NON_NULL) resp. #JsonSerialize(include=Include.NON_NULL).