How to force some customer to be serviced by a specific vehicle in VRP examples of the OptaPlanner? - drools

In the VRP examples of Optaplanner, I would like to force some customer to be serviced by a specific vehicle in VRP.
How to do this? Can anyone help me?

There are several ways. The easiest is probably just to add a hard constraint
when
Customer(forcedVehicleIsNotVehicle == true)
then
scoreHolder.addHardConstraint...
end
class Customer {
public boolean isForcedVehicleIsNotVehicle() {
return forcedVehicle != null
&& vehicle != null && forcedVehicle != vehicle;
}
}

Related

Split incoherent aggregates

the most common way to implement aggregates is to create a god class with enum status and "if-ladder", like below:
public class Order {
private OrderId id;
private PropertyA a;
private PropertyB b;
private OrderStatus status;
public void doSthWithA() {
if(status != OrderStatus.A) {
//throw illegal argument
}
//do sth with PropertyA
status = OrderStatus.B;
}
public void doSthWithB() {
if(status != OrderStatus.B) {
//throw illegal argument
}
//do sth with PropertyB
}
}
Order class isn not coherent, because doSthWithA uses PropertyA and doSthWithB uses PropertyB.
Isn't better way doing it in this way:
public class OrderA {
private OrderId id;
private PropertyA a;
public OrderB doSthWithA() {
//do sth with PropertyA
return new OrderB(id);
}
}
public class OrderB {
private OrderId id;
private PropertyB b;
public void doSthWithB() {
//do sth with PropertyB
}
}
?
Anyway I have a question. We could persist both aggregates in one table ORDER or two tables: ORDER_A and ORDER_B.
But what are strategies to test which order state is newest?
Let's assume that someone saves OrderA to DB, next executes doSthWithA and saves OrderB to DB.
Futher when we do some query how could we resolve the newest state? Should we add some version or timestamp to aggregates?
And what about REST services?
With one god class Order the REST services could look like:
/orders/{id}/do-sth-with-a and
/orders/{id}/do-sith-with-b
With second solution could we have:
/a-orders/{id}/do-sth-with-a and
/b-orders/{id}/do-sith-with-b
?
Isn't better way doing it in this way
Not necessarily better, because there are trade offs. However, it is common that the benefits of a design with smaller aggregates outweigh the costs.
Vaughn Vernon, in Implementing Domain Driven Design, proposes the rule "Design Small Aggregates".
Roughly, each aggregate "should" enclose coupled information; typically graphs of values that must be internally "consistent". If you find that your values form two discrete sets that have only a single identifier in common, that's a good sign that there is an opportunity to reduce the aggregate further.
We could persist both aggregates in one table ORDER or two tables: ORDER_A and ORDER_B. But what are strategies to test which order state is newest?
Real answer: if you actually care about "newest", then you should be modeling time in your domain logic.
It's not uncommon to throw general purpose timing information into a design, but you want to be careful about entangling general purpose timing used for operation and analysis from your domain timing.
And what about REST services?
Your resource model is not your domain model. Having a single "god" resource in your resource model has a completely different set of trade offs from "god" aggregates in your domain model.
It's completely normal to have one web resource that renders information from multiple aggregates.

MapStruct: Map two sources and return null if one of them is null

I could not find an answer and I believe this is not possible with MapStruc. I would like to ask anyway, maybe I missed something.
I have a mapping method that takes two sources and maps to one target, let's say
#Mapping(...)
#Mapping(...)
...
Target mapToTarget(SourceA a, SourceB b);
The generated code does the following null check to return null:
if (a == null && b == null) return null;
I wish to have
if (a == null || b == null) return null;
For the moment I filter beforehand so that I won't give null as input. I wish to skip that part and simply return null in the mapper if an argument is null.
Does MapStruct support this?
P.S.: We use MapStruct 1.3.1
This is not possible with MapStruct. However, you can achieve this by providing a default method.
e.g.
#Mapper
public abstract class CustomerMapper {
public Target mapToTarget(SourceA a, SourceB b) {
if (a == null || b == null) {
return null;
}
return mapToTargetWithMapStruct(a, b);
}
#Named("ignore") // #Named in order for MapStruct not to consider this as a candidate
protected abstract mapToTargetWithMapStruct(SourceA a, SourceB b);
}

Querying against DbContext.Set(TypeVariable) in Entity Framework

I'm re-factoring an application to invert some dependencies. Part of the original code uses DbContext.Set<MyEntityType>() to obtain the set to query against.
With the inversion, the MyEntityType is no longer explicitly known to the code using DbContext.Set<MyEntityType>(), so now I'm using DbContext.Set(TypeVariable) instead.
The re-factoring works to the extent that the correct DbSet is being returned.
However, the type DbContext.Set(TypeVariable).Local is IList (contained type unknown) where-as the type of DbContext.Set<MyEntityType>().Local was ObservableCollection<MyEntityType>. This means that it's now impossible to do Linq against the DbSet.
The best workaround I've been able to achieve is to cast to an interface that MyEntityType and other entity types implement (some code omitted for clarity)
var set = Context.Set(targetType);
var entity = set.Local.OfType<IActionTarget>()
.FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
var querables = set as IQueryable<IActionTarget>;
entity = querables.FirstOrDefault(e => e.Id == key.Id && e.EffectiveDate == key.EffectiveDate);
So, two questions:
Why doesn't DbContext.Set(TypeVariable) return a strongly typed set?
Is there a better way to do the dependency inversion?
Some further details as requested
It's all about dependencies. The Model contains POCO classes which are persisted via EF Code First in the typical way (but via a Repository). An ActionEvaluator takes some incoming data, and via Repository methods, determines what actions need to occur - hence the queries against the DbSets.
In the original code, there was only one type of incoming data (CSV of a particular format) and the ActionEvaluator had a tight dependency to this data and knew which POCO classes were applicable to which CSV records.
Now, we want to expand to use different CSV formats and web api messages. To do this, we need to invert the dependencies so that the DataSource tells the ActionEvaluator what POCO classes it's records apply to. This is done by way of a Type variable.
So, the ActionEvaluator can no longer use a generic type parameter, but it can pass the type variable to the Repository which uses it to find the correct DbSet.
The problem is the difference between the two ways of finding the DbSet - DbContext.Set<AnEntity>() and DbContext.Set(TypeVariable).
I guess I'm asking for an enhancement in EF to make these two functionally equivalent in their return values, but that may not be possible since the types of the second version are determined at runtime.
Here's the full method code as requested:
private IActionTarget DbContextGetEntity(Type targetType, IActionTarget key)
{
var set = Context.Set(targetType);
if (set == null)
{
throw new Exception("Unable to find DbSet for type '{0}'".F(targetType.Name));
}
// Look in the local cache first
var entity = set.Local.OfType<IActionTarget>()
.FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
if (entity == null)
{
// If not found locally, hit the database
var querables = set as IQueryable<IActionTarget>;
if (querables != null)
{
entity = querables.FirstOrDefault(e => e.Id == key.Id && e.EffectiveDate == key.EffectiveDate);
}
}
return entity;
}
Ideally, I want to replace
var entity = set.Local.OfType<IActionTarget>()
.FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
with
var entity = set.Local.OfType(targetType)
.FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
I haven't compiled it so please excuse any formatting issues - can you use the dynamic type to achieve the same thing?
private IActionTarget DbContextGetEntity(Type targetType, IActionTarget key)
{
dynamic instance = Activator.CreateInstance(targetType);
return DbContextGetEntity(instance, key);
}
private IActionTarget DbContextGetEntity<T>(T instance, IActionTarget key)
where T : class, IActionTarget
{
var set = Context.Set<T>(targetType);
if (set == null)
{
throw new Exception();
}
// Look in the local cache first
var entity = set.Local
.FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
if (entity == null)
{
// If not found locally, hit the database
entity = set
.FirstOrDefault(e => e.Id == key.Id && e.EffectiveDate == key.EffectiveDate);
}
return entity;
}

how to judge the abstract class with ICompilationUnit

I am working on the eclipse plugin development,so I find the api docs and google them,it only contains such method isClass() isInterface() with the ICompilationUnit,but I want to dig deep with the abstract class,the code like
public boolean isAbstract(ICompilationUnit icu) {
//TODO
}
can anybody help me?
First, you will need an instance of org.eclipse.jdt.core.IType, because one ICompilationUnit can contain several types. ICompilationUnit.getTypes() will provide you with list of all types in this unit. ICompilationUnit.findPrimaryType() will get you a primary type for this unit.
Your routine should look something like following:
public boolean isAbstract(ICompilationUnit icu) throws JavaModelException {
final IType type = icu.findPrimaryType();
return (type != null)
? Flags.isAbstract(type.getFlags())
: false;
}
where Flags is org.eclipse.jdt.core.Flags.

asp.net MVC 2 - most elegant way of isolating guard code - guarding against null controller parameters

I have a very simple problem, but I'm looking for the 'best' solution to the following:
I have multiple controller actions something like this:
public ActionResult DoSomething(PackageViewModel packageByName, DoSomethingInputModel inputModel)
{
if (packageByName == null)
{
Response.StatusCode = 404;
Response.StatusDescription = "Package not found : " + RouteData.GetRequiredString("packageName");
return View("Error");
}
...
What is the best way to isolate this cross cutting concern?
I can make a function
I can use an AOP tool like PostSharp
ActionFilter
Other?
In fact ActionFilter is an AOP. Write your own ActionFilter implementation to chceck if parameter is not null. If you always need to check the same thing on the beggining of your controller execution then it's the best way. It's easy to write, resusable in whole application and very MVC 2.
Here's what I implemented (based on #ƁukaszW.pl answer)
Hopefully this will save someone some time.
public class GuardAgainstNullPackage : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
BookingController controller = ((BookingController)filterContext.Controller);
if (filterContext.ActionParameters["packageByName"] == null || !(filterContext.ActionParameters["packageByName"] is PackageViewModel))
{
controller.Response.StatusCode = 404;
controller.Response.StatusDescription = "Package not found : " + filterContext.RouteData.GetRequiredString("packageName");
filterContext.Result = new ViewResult() { ViewName = "Error" };
}
base.OnActionExecuting(filterContext);
}
}