Can I force mapstruct to delegate a mapping method to another mapping method or a default (builtin) conversion? - mapstruct

Can I force mapstruct to delegate a mapping method to another mapping method or a default (builtin) conversion?
I basically would like to access a custom mapping method of a uses MapperA inside the custom mapping method of the using MapperX. But I can't get a hold of the injected MapperA inside the custom mapping method of MapperX.
The same is true for builtin conversions. I want to make use of a builtin conversion of mapstruct inside a custom method. Like convert from Date to ZonedDateTime.
e.g.:
#Mapper(componentModel="cdi")
public interface MapperA {
A fromB(B b);
default Q fromR(R r) {
Q q = ..<do some stuff with r>..
return q;
}
}
#Mapper(componentModel="cdi"
uses = MapperA.class
)
public interface MapperX {
default X custom(Y y) {
Date someJavaUtilDate = customDateFromY(y);
//I dont want to code Date->ZonedDateTime myself
//I want mapstruct to do its builtin conversion, so call placeholder:
X.myZonedDateTime = builtinConversionPlaceholder(someJavaUtilDate)
R r = ..<do some stuff with y>..
X.q = usesMapperPlaceholder(r); // injected "uses MapperA" is not directly accessible here?
}
#org.mapstruct.Find_Me_A_Matching_Method_Builtin_Or_In_Uses_Mapper
// will not map properties of Date to ZonedDateTime
// but will use mapstruct builtin conversion code
ZonedDateTime builtinConversionPlaceholder(java.util.Date date);
#org.mapstruct.Find_Me_A_Matching_Method_Builtin_Or_In_Uses_Mapper
// will delegate to MapperA.fromR
Q usesMapperPlaceholder(R r);
}

No it is not possible to force MapStruct to use. build in conversion method.
What you can do is to create some wrapper objects that will be mapped between java.util.Date and ZonedDateTime, MapStruct will then map those using the built in mappings.
e.g.
#Mapper(componentModel="cdi")
public interface MapperA {
A fromB(B b);
default Q fromR(R r) {
Q q = ..<do some stuff with r>..
return q;
}
}
#Mapper(componentModel="cdi"
uses = MapperA.class
)
public abstract class MapperX {
#Inject
MapperA mapperA;
default X custom(Y y) {
Date someJavaUtilDate = customDateFromY(y);
X.myZonedDateTime = toZonedDateTime(someJavaUtilDate).getValue();
R r = ..<do some stuff with y>..
X.q = mapperA.fromR(r);
}
Wrapper<ZonedDateTime> toZonedDateTime(Wrapper<java.util.Date> date);
static class Wrapper<T> {
private T value;
//getters and setters
}
}

Related

Assign Mapped Object to Expression Result in LINQ to Entities

I have the following child object that we use an expression to map our 'entity' to our 'domain' model. We use this when specifically calling our ChildRecordService method GetChild or GetChildren:
public static Expression<Func<global::Database.Models.ChildRecord, ChildRecord>> MapChildRecordToCommon = entity => new ChildRecord
{
DateTime = entity.DateTime,
Type = entity.Type,
};
public static async Task<List<ChildRecord>> ToCommonListAsync(this IQueryable<global::Database.Models.ChildRecord> childRecords)
{
var items = await
childRecords.Select(MapChildRecordToCommon).ToListAsync().EscapeContext();
return items;
}
public async Task<List<ChildRecord>> GetChildRecords()
{
using (var uow = this.UnitOfWorkFactory.CreateReadOnly())
{
var childRecords= await uow.GetRepository<IChildRecordRepository>().GetChildRecords().ToCommonListAsync().EscapeContext();
return childRecords;
}
}
So that all works just fine. However we have another object that is a parent to that child, that in SOME cases, we also wish to get the child during the materialisation and mapping process.
In other words the standard object looks as such:
private static Expression<Func<global::Database.Models.Plot, Plot>> MapPlotToCommonBasic = (entity) => new Plot
{
Id = entity.Id,
Direction = entity.Direction,
Utc = entity.Utc,
Velocity = entity.Velocity,
};
However what I also want to map is the Plot.ChildRecord property, using the expression MapChildRecordToCommon I have already created. I made a second expression just to test this:
private static Expression<Func<global::Database.Models.Plot, Plot>> MapPlotToCommonAdvanced = (entity) => new Plot
{
ChildRecord = MapChildRecordToCommon.Compile() (entity.ChildRecord)
};
This fails:
System.NotSupportedException
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
Is there a way to reuse my existing expression for ChildRecord, to materialise the object of ChildRecord (ie. one to one/singular not multiple) on the Plot object? I think my trouble is caused by there being just one object and being unable to use the .Select(Map) method. I am not too great at expressions and have hit a wall with this.
For reference, there are actually up to 5 or 6 other child objects on the "Plot" object that I also want to make expressions for.
I resolved this by using the third party library LinqKit.
The library allowed the use of 2 methods, .AsExpandable() (which allows for the expressions to properly compile and be invoked as I understand), and .Invoke() as an extension method to an expression, rather than calling Expression.Invoke(yourexpression). I included a null check just in case.
My code now looks as follows:
public static async Task<List<Plot>> ToCommonListAsync(this IQueryable<global::Database.Models.Plot> plots)
{
var items = await
plots.AsExpandable().Select(MapPlotToCommon).ToListAsync().EscapeContext();
return items;
}
private static Expression<Func<global::Database.Models.Plot, Plot>> MapPlotToCommon = (entity) => new Plot
{
Id = entity.Id,
Direction = entity.Direction,
Utc = entity.Utc,
Velocity = entity.Velocity,
ChildRecord = entity.ChildRecord != null ? MapChildRecordToCommon.Invoke(entity.ChildRecord) : default
};
public static Expression<Func<global::Database.Models.ChildRecord, ChildRecord>> MapChildRecordToCommon = entity => new ChildRecord
{
DateTime = entity.DateTime,
Type = entity.Type,
};

Difference between assign values for the variables of a class [duplicate]

This question already has answers here:
Should I initialize variable within constructor or outside constructor [duplicate]
(11 answers)
Closed 6 years ago.
What is the difference between below 2 ways of assigning values for variables of a class.
Class A{
Private Variable v = someValue;
}
vs
Class A{
private Variable v;
//constructor
public A(){
this.v = someValue;
}
}
Can someone please explain?
There is no real difference from a code execution point of view.
As a previous answer says, I prefer declaring the variable outside of the constructor; for example:
public class A {
private int aValue = 100;
}
Instead of
public class A {
private int aValue;
public A() {
this.aValue = 100;
}
}
The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.
As others have said however, there are times when it is better to initialize the variable in the constructor.
If it will change based on values passed to it via the constructor, obviously initialize it there.
If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor
If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.
Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).
See this duplicate answer: https://stackoverflow.com/a/3919225/1274820
What is the difference between below 2 ways of assigning values for
variables of a class.
Generally nothing, but ...
class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.
When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.
public class C {
private int aValue;
private int bValue;
private int cValue;
private int dValue;
public C(int a, int b) {
this.aValue = a;
this.bValue = b;
this.cValue = a * b;
this.dValue = 1000;
}
}
If you look at the MSIL of this class:
namespace Demo
{
public class MyClass
{
private string str = "hello world";
private int b;
public MyClass(int b)
{
this.b = b;
}
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 b) cil managed
{
// Code size 25 (0x19)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "hello world"
IL_0006: stfld string Demo.MyClass::str <---- RIGHT HERE
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: ldarg.0
IL_0012: ldarg.1
IL_0013: stfld int32 Demo.MyClass::b
IL_0018: ret
} // end of method MyClass::.ctor
You can see that the constructor is "injected" with the assignment of this.str = "hello world".
So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)

Ninject scoping - use same instance across entire graph being constructed

Let's say I have the following classes that I want to construct using Ninject, with the arrows showing dependencies.
A > B > D
A > C > D
I want to configure Ninject such that A is transient scoped, i.e. every time you ask Ninject for an A, you get a new one. I also want B and C to be transient, you get a new one of those every time you ask for an A. But I want the D to be reused across both B and C. So every time I request an A, I want Ninject to construct one of each object, not two Ds. But I don't want Ds to be reused across different As.
What is the best way to set this up using Ninject?
Update:
After some more research, it seems like Unity has a PerResolveLifetimeManager which does what I'm looking for. Is there a Ninject equivalent?
Ninject supports four built in object scopes out of the box: Transient, Singleton, Thread, Request.
So there isn't any PerResolveLifetimeManager like scope but you can implement it easily with registering a custom scope with the InScope method.
As it turned out there is an existing Ninject extension: ninject.extensions.namedscope which provides the InCallScope method which is what you are looking for.
However if you want to do it yourself you can do with a custom InScope delegate. Where you can use the main IRequest object for the type A to use it as the scope object:
var kernel = new StandardKernel();
kernel.Bind<A>().ToSelf().InTransientScope();
kernel.Bind<B>().ToSelf().InTransientScope();
kernel.Bind<C>().ToSelf().InTransientScope();
kernel.Bind<D>().ToSelf().InScope(
c =>
{
//use the Request for A as the scope object
var requestForA = c.Request;
while (requestForA != null && requestForA.Service != typeof (A))
{
requestForA = requestForA.ParentRequest;
}
return requestForA;
});
var a1 = kernel.Get<A>();
Assert.AreSame(a1.b.d, a1.c.d);
var a2 = kernel.Get<A>();
Assert.AreSame(a2.b.d, a2.c.d);
Assert.AreNotSame(a1.c.d, a2.c.d);
Where the sample classes are:
public class A
{
public readonly B b;
public readonly C c;
public A(B b, C c) { this.b = b; this.c = c; }
}
public class B
{
public readonly D d;
public B(D d) { this.d = d; }
}
public class C
{
public readonly D d;
public C(D d) { this.d = d; }
}
public class D { }
I found the solution to my specific problem, which is InCallScope that is provided by the ninject.extensions.namedscope extension. This behaves identically to the Unity PerResolveLifetimeManager concept.
One alternative is to construct the dependencies yourself.
var kernel = new StandardKernel();
kernel.Bind<A>().ToMethod(ctx =>
{
var d = new D();
var c = new C(d);
var b = new B(d);
var a = new A(b, c);
return a;
});
This may not be the preferred method, but it will always construct a new instance of A using a new instance of B, C, and D (but reusing the same instance of D for B and C). You can add a call to InTransientScope(), but that is not required as it is the default scope.

How to handle optional query parameters in Play framework

Lets say I have an already functioning Play 2.0 framework based application in Scala that serves a URL such as:
http://localhost:9000/birthdays
which responds with a listing of all known birthdays
I now want to enhance this by adding the ability to restrict results with optional "from" (date) and "to" request params such as
http://localhost:9000/birthdays?from=20120131&to=20120229
(dates here interpreted as yyyyMMdd)
My question is how to handle the request param binding and interpretation in Play 2.0 with Scala, especially given that both of these params should be optional.
Should these parameters be somehow expressed in the "routes" specification? Alternatively, should the responding Controller method pick apart the params from the request object somehow? Is there another way to do this?
Encode your optional parameters as Option[String] (or Option[java.util.Date], but you’ll have to implement your own QueryStringBindable[Date]):
def birthdays(from: Option[String], to: Option[String]) = Action {
// …
}
And declare the following route:
GET /birthday controllers.Application.birthday(from: Option[String], to: Option[String])
A maybe less clean way of doing this for java users is setting defaults:
GET /users controllers.Application.users(max:java.lang.Integer ?= 50, page:java.lang.Integer ?= 0)
And in the controller
public static Result users(Integer max, Integer page) {...}
One more problem, you'll have to repeat the defaults whenever you link to your page in the template
#routes.Application.users(max = 50, page = 0)
In Addition to Julien's answer. If you don't want to include it in the routes file.
You can get this attribute in the controller method using RequestHeader
String from = request().getQueryString("from");
String to = request().getQueryString("to");
This will give you the desired request parameters, plus keep your routes file clean.
Here's Julien's example rewritten in java, using F.Option: (works as of play 2.1)
import play.libs.F.Option;
public static Result birthdays(Option<String> from, Option<String> to) {
// …
}
Route:
GET /birthday controllers.Application.birthday(from: play.libs.F.Option[String], to: play.libs.F.Option[String])
You can also just pick arbitrary query parameters out as strings (you have to do the type conversion yourself):
public static Result birthdays(Option<String> from, Option<String> to) {
String blarg = request().getQueryString("blarg"); // null if not in URL
// …
}
For optional Query parameters, you can do it this way
In routes file, declare API
GET /birthdays controllers.Application.method(from: Long, to: Long)
You can also give some default value, in case API doesn't contain these query params it will automatically assign the default values to these params
GET /birthdays controllers.Application.method(from: Long ?= 0, to: Long ?= 10)
In method written inside controller Application these params will have value null if no default values assigned else default values.
My way of doing this involves using a custom QueryStringBindable. This way I express parameters in routes as:
GET /birthdays/ controllers.Birthdays.getBirthdays(period: util.Period)
The code for Period looks like this.
public class Period implements QueryStringBindable<Period> {
public static final String PATTERN = "dd.MM.yyyy";
public Date start;
public Date end;
#Override
public F.Option<Period> bind(String key, Map<String, String[]> data) {
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
try {
start = data.containsKey("startDate")?sdf.parse(data.get("startDate") [0]):null;
end = data.containsKey("endDate")?sdf.parse(data.get("endDate")[0]):null;
} catch (ParseException ignored) {
return F.Option.None();
}
return F.Option.Some(this);
}
#Override
public String unbind(String key) {
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
return "startDate=" + sdf.format(start) + "&" + "endDate=" + sdf.format(end);
}
#Override
public String javascriptUnbind() {
return null;
}
public void applyDateFilter(ExpressionList el) {
if (this.start != null)
el.ge("eventDate", this.start);
if (this.end != null)
el.le("eventDate", new DateTime(this.end.getTime()).plusDays(1).toDate());
}
}
applyDateFilter is just a convienence method i use in my controllers if I want to apply date filtering to the query. Obviously you could use other date defaults here, or use some other default than null for start and end date in the bind method.

Using function result inside expression function used by a predicate

I am trying to use predicateBuilder with next expression definition but I always got the message
"LINQ to Entities does not recognize the method 'puedeConsultar' method, and this method cannot be translated into a store expression."
I think i understand more less this problem, but i don´t know how to solve it.
private static readonly IDictionary<int, List<string>> permisosAccesoSolicitudesEstado = new Dictionary<int, List<string>>(){{0, new List<string>(){"A"}}, {1, new List<string>(){"B"}}};
private static bool esPermisoConcedido(List<string> usuariosPermitidos, string erfilUsuario)
{
return usuariosPermitidos.Any(x => x.Equals(perfilUsuario) || perfilUsuario.StartsWith(x + "|") || perfilUsuario.EndsWith("|" + x));
}
public static bool puedeConsultar(int estadoActual, string perfilUsuario)
{
List<string> usuariosPermitidos = permisosAccesoSolicitudesEstado[estadoActual];
return esPermisoConcedido(usuariosPermitidos, perfilUsuario);
}
public static bool puedeConsultar(string estadoActual, string tipoUsuario)
{
return puedeConsultar(Convert.ToInt32(estadoActual), tipoUsuario);
}
public Expression<Func<Solicitud, Boolean>> predicadoEstadoCorrectoSolicitud(string perfil)
{
return x=> EstadosSolicitud.puedeConsultar(x.estado, perfil);
}
//Instantiated by reflection, this works fine
MethodInfo method = .....
Expression<Func<T, bool>> resultado = ConstructorPredicados.True<T>();
resultado = ConstructorPredicados.And(resultado, method);
objectSet.Where(resultado).ToList();
Note:
ConstructorPredicados is based in Monty´s Gush "A universal PredicateBuilder" on http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/
Thanks in advance
You cannot do that. Your puedeConsultar is .NET function. You cannot execute .NET functions in Linq-to-entities query. When you use method in Linq-to-entities you can use only methods which has direct mapping to SQL. It means that method in the query is only placeholder which is translated to execution of some SQL function. There is set of predefined method mappings called cannonical functions and you can map your own SQL function when using EDMX but in your case you will most probably have to first load data to application by using ToList and after that execute predicadoEstadoCorrectoSolicitud on materialized result.