Java : set generic parameters for a method - java-8

I have a method that can take ResponseEntity as parameter.
private ResponseEntity<OfferRest> mappedOfferByImagesEnabled(
ResponseEntity<OfferRest> offerResponse) {
for (OfferDetailImageRest image :
offerResponse.getBody().getOfferDetail().getImages()) {
if (image.getDisabled()) {
return offerResponse;
}
}
return null;
}
I have the same method with another parameters: OfferEnity and I don't have need to call getBody() like the other one.
private OfferEntity mappedOfferByImagesEnabled(OfferEntity offerEntity) {
for (OfferDetailImageEntity image :
offerEntity.getOfferDetail().getImages()) {
if (image.getDisabled()) {
return offerEntity;
}
}
return null;
}
My idea is to have a method with one (generic) parameter. Basing on the settings instance I will run the convenient code.
My question, How can I do it?

You can create a method with OfferDetail parameter
public boolean isImageDisabled(OfferDetail offerdetail) {
return offerdetail.getImages().stream().anyMatch(Image::getDisabled));
}
And the use it
isImageDisabled(offerEntity.getOfferDetail());
isImageDisabled(offerResponse.getBody().getOfferDetail());

Related

Mono<Object> being returned instead of Mono<ResponseEntity> when mapping (Java 8)

Trying to practice reactive coding for an API but I'm struggling to understand what I'm doing wrong when using flatMap() and map() to cast to a ResponseEntity object. The error mentions that the code is returning a Mono<Object> and cant be cast/transformed into a Mono<ResponseEntity<>>.
Public Mono<ResponseEntity<?> deleteEndpoint(String someId) {
return db.existsById(someId).flatMap(exists -> {
if (!exists) return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
else {
Mono<Boolean> deletedStuff1 = someFunct();
Mono<Boolean> deletedStuff2 = anotherFunct();
Mono<Tuple2<Boolean, Boolean>> deletedStuff = Mono.zip(deletedStuff1, deletedStuff2);
return deletedStuff.then(Mono.just(ResponseEntity.status(NO_CONTENT).build());
}
});
}
All help is appreciated
From .flatMap() you must return Publisher, not actual object
In this if statement you return ResponseEntity instead of Mono<ResponseEntity>
So, just wrap it with Mono
if (!exists) {
return Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST).build());
} else {
// ...

DelegateEndpointDefinition IsTemporary

I have a simple ConsumerDefinition:
public class HealthCheckConsumerDefinition : ConsumerDefinition<LoopbackConsumer>
{
public HealthCheckConsumerDefinition(IOptions<HealthCheckOptions> options)
{
EndpointName = options.Value.HostName;
Endpoint(configurator => configurator.Temporary = true); // not work
}
protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator, IConsumerConfigurator<LoopbackConsumer> consumerConfigurator)
{
endpointConfigurator.ConfigureConsumeTopology = false;
base.ConfigureConsumer(endpointConfigurator, consumerConfigurator);
}
}
I expect the Temporary=true property to configure an endpoint with the AutoDelete = true and Durable = false properties, because this code is in the ApplyEndpointDefinition method of the RabbitMqHostConfiguration class:
https://github.com/MassTransit/MassTransit/blob/5fb6b4e31582970b0571e9fe6ac77793a0b3242a/src/MassTransit.RabbitMqTransport/Configuration/Configuration/RabbitMqHostConfiguration.cs#L60
public void ApplyEndpointDefinition(IRabbitMqReceiveEndpointConfigurator configurator, IEndpointDefinition definition)
{
if (definition.IsTemporary)
{
configurator.AutoDelete = true;
configurator.Durable = false;
}
...
}
But in the ConfigureEndpoints method of the class, the ConsumerDefinition registry is converted to the DelegateEndpointDefinition, which does not override the IsTemporary property based on the ConsumerDefinition object passed to the constructor:
https://github.com/MassTransit/MassTransit/blob/89ba77036230a15be108e8ade3a0e6fe5309a94d/src/MassTransit/Configuration/Registration/Registration.cs#L178
How to get around this problem and declare Temporary endpoint within the ConsumerDefinition?
I have confirmed that this works as expected in the upcoming MassTransit v7 release. Using this syntax, the temporary flag is now passed through to the transport.
Note that this would be overridden by using .Endpoint() following the AddConsumer<T>() container configuration method.
class RequestConsumerDefinition :
ConsumerDefinition<RequestConsumer>
{
public RequestConsumerDefinition()
{
Endpoint(e => e.Temporary = true);
}
}

Laravel 4 - dependency injection based on configuration?

I have an interface
interface RecordsService {
public function getRecords();
}
and two implementations:
public class ApiRecordsService implements RecordsService {
public function getRecords() {
//get records from api
}
}
public class DbRecordsService implements RecordsService {
public function getRecords() {
//get records from db
}
}
Now, in my controller I do DI like this:
class RecordsController {
private $recordsService;
public function __construct(RecordsService $recordsService) {
$this->recordsService= $recordsService;
}
}
And I bind it like this:
App::bind('RecordsService', 'ApiRecordsService');
Now, my question is, is it possible to implement this more dynamically, based on configuration, something like this:
switch( Config::get('config.records_source') ){
case 'db':
App::bind('RecordsService', 'DbRecordsService');
break;
case 'api':
App::bind('RecordsService', 'ApiRecordsService');
break;
}
and more important, is this a good practice ?
You can use for that an annonymous function like that:
App::bind('RecordsService', function() {
switch( Config::get('config.records_source') ){
case 'db':
return new DbRecordsService;
case 'api':
return new ApiRecordsService;
}
});

Webflow get Event Id in Controller

Is there a way to get the _eventId parameter from the SWF RequestContext? Sometimes I need to use a bit of logic to decide where to transition to:
public String processATransition(RequestContext requestContext) {
String eventId = ?
if (eventId.equals("PREV")) {
if (currentViewState.equals("search")) {
return "searchParameters";
} else {
return "start";
}
}
}
Any help would be appreciated.
You can get it by:
String eventId = requestContext.getCurrentEvent().getId();

DI with parameters in Castle Windsor

I'm trying to resolve a dependency like this:
controller.ActionInvoker = kernel.Resolve<IActionInvoker>(controller.GetType());
It was previously registered in this way:
container.Register(
Component
.For<IActionInvoker>()
.ImplementedBy<WindsorActionInvoker>()
.UsingFactoryMethod(metho)
.LifestylePerWebRequest()
);
internal IActionInvoker metho(IKernel kernel,ComponentModel model, CreationContext context)
{
// here just for debugging and watching the variables in the factory method,
// I would instance WindsorActionInvoker passing the filters to inject.
throw new InvalidOperationException();
}
But I can't figure out how to get the parameter I passed to the resolve call in the factory method.
I need the Type I'm passing as parameter to pass it to one of the dependencies injected into the constructor of the concrete type.
What am I doing wrong?
If you must know, the purpose of this is to inject action filters directly into the action invoker (and therefore the controllers), instead of requiring them decorate a controller or the base controller, additionally, this lets me to inject parameters dynamically, which I can't do with attributes.
public class WindsorActionInvoker : ControllerActionInvoker
{
private readonly IList<IActionFilter> actionFilters;
private readonly IList<IAuthorizationFilter> authorizationFilters;
private readonly IList<IExceptionFilter> exceptionFilters;
private readonly IList<IResultFilter> resultFilters;
public WindsorActionInvoker(IList<IActionFilter> actionFilters, IList<IAuthorizationFilter> authorizationFilters, IList<IExceptionFilter> exceptionFilters, IList<IResultFilter> resultFilters)
{
if (actionFilters == null)
{
throw new ArgumentNullException("actionFilters");
}
if (authorizationFilters == null)
{
throw new ArgumentNullException("authorizationFilters");
}
if (exceptionFilters == null)
{
throw new ArgumentNullException("exceptionFilters");
}
if (resultFilters == null)
{
throw new ArgumentNullException("resultFilters");
}
this.actionFilters = actionFilters;
this.authorizationFilters = authorizationFilters;
this.exceptionFilters = exceptionFilters;
this.resultFilters = resultFilters;
}
protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
FilterInfo filterInfo = base.GetFilters(controllerContext, actionDescriptor);
foreach (IActionFilter filter in actionFilters)
{
filterInfo.ActionFilters.Add(filter);
}
foreach (IAuthorizationFilter filter in authorizationFilters)
{
filterInfo.AuthorizationFilters.Add(filter);
}
foreach (IExceptionFilter filter in exceptionFilters)
{
filterInfo.ExceptionFilters.Add(filter);
}
foreach (IResultFilter filter in resultFilters)
{
filterInfo.ResultFilters.Add(filter);
}
return filterInfo;
}
}
Solved, I needed to pass either a dictionary or an anonymous type instead of just any object.
Replacing:
controller.ActionInvoker = kernel.Resolve<IActionInvoker>(controller.GetType());}
With
controller.ActionInvoker = kernel.Resolve<IActionInvoker>(new { loggerType = controller.GetType() });
Fixed it.
:)

Resources