Need to invoke same controller method for different api's - java

I have 2 APIs
1. localhost:8080/myservice/foo/1/0/updatesStatus
2. localhost:8080/myservice/bar/1/0/updatesStatus
I am not allowed to have different controllers for each API. So both the APIs are pointing to the same controller method where I have if-else check, but the code looks very bad in that, is there any better way to handle this.
#PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(#PathVariable("group") String group , #RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
try {
if(APIUrl.FOO_GROUP.equals(group)){
//code spefic to foo
}
else{
//code spefic to bar
}
//common code
}
The same conditional checks also have to be performed on the service layer as well.
Is there any way I can avoid this conditional checks without having separate controller methods.

I can think of this.
Create an interface for service.
public interface UpdateService {
void updateStatus(UpdateStatusRequest updateStatusRequest);
}
Then you create different implementations.
public class FooUpdateService implements UpdateService {
void updateStatus(UpdateStatusRequest updateStatusRequest) {
// foo specific logic
}
}
public class BarUpdateService implements UpdateService {
void updateStatus(UpdateStatusRequest updateStatusRequest) {
// Bar specific logic
}
}
Create a UpdateServiceFactory
public class UpdateServiceFactory {
#Autowired
private UpdateService fooUpdateService;
#Autowired
private UpdateService fooUpdateService;
public UpdateService getUpdateService(String group) {
// Move the if-else logic here
if(APIUrl.FOO_GROUP.equals(group)){
return fooUpdateService;
}
else{
//code spefic to bar
return barUpdateService;
}
}
}
Controller:
#PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(#PathVariable("group") String group , #RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
updateServiceFactory.getUpdateService(group).updateStatus(updateStatusRequest);
//common code
}

Related

Incorporating Guice and AOP

I'm building a package that is trying to intercept a function's return value based on a flag. My design involves some AOP. The idea is that a class FirstIntercept intercepts a call firstCall and stores parameters in a Parameters object. Then later, a second class SecondIntercept intercepts another call secondCall and does some logic based on what is populated in Parameters:
// pseudoish code
public class FirstIntercept {
private Parameters param;
#AfterReturning(pointcut = "execution(* ...firstCall(..))", returning = "payload")
public void loadParam(Joinpoint joinPoint, Object payload) {
// logic handling payload returned from firstCall()
// logic provides a Boolean flag
this.param = new Parameters(flag);
}
}
public class Parameters {
#Getter
private Boolean flag;
public Parameters(Boolean flag) {
this.flag = flag;
}
}
public class SecondIntercept {
private static Parameters params;
#Around("execution(* ...secondCall(..))")
public void handleSecondCallIntercept(ProceedingJoinPoint joinPoint) {
// want to do logic here based on what params contains
}
}
What I want to achieve is that the Parameters object is loaded once and for all when FirstIntercept.loadParam is invoked through AOP. I'm not too sure how I can go about with this persistence. I looked online and Google guice seems to be promising. I believe a first step would to use dependency injection on the Parameters, but I'm really not sure. Can someone help point me in the right direction?
edit:
So I tried this setup:
public class FirstIntercept implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("invoked!");
return invocation.proceed();
}
#AfterReturning(pointcut = "execution(* ...firstCall(..))", returning = "payload")
public void loadParam(Joinpoint joinPoint, Object payload) {
// do stuff
}
public String firstCall() {
return "hello";
}
}
public class InterceptionModule extends AbstractModule {
protected void configure() {
FirstIntercept first = new FirstIntercept();
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AfterReturning.class), first);
}
}
public class FirstIterceptTest {
#Test
public void dummy() {
Injector injector = Guice.createInjector(new InterceptionModule());
FirstIntercept intercept = injector.getInstance(FirstIntercept.class);
intercept.firstCall();
}
}
When I do .firstCall(), I can see the #AfterReturning running but the invoke is not being called.
If you expand upon the documentation for AOP https://github.com/google/guice/wiki/AOP you should get something close to:
public class FirstInterceptor implements MethodInterceptor {
#Inject Parameters parameters; // Injected with singleton Parameter
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = invocation.proceed();
// your logic based on result to set parameters.setFlag()
return result;
}
}
Then the second:
public class SecondInterceptor implements MethodInterceptor {
#Inject Parameters parameters; // Injected with singleton Parameter
public Object invoke(MethodInvocation invocation) throws Throwable {
boolean flag = parameters.getFlag();
// your logic here
return invocation.proceed(); // maybe maybe not?
}
}
Your parameters is the key, you'll need to ensure it's thread safe, which is another topic. But to inject these you need:
public class InterceptionModule extends AbstractModule {
protected void configure() {
// Ensure there is only ever one Parameter injected
bind(Parameter.class).in(Scopes.SINGLETON);
// Now inject and bind the first interceptor
FirstInterceptor firstInterceptor = new FirstInterceptor();
requestInjection(firstInterceptor );
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AfterReturning.class),
firstInterceptor);
// Now inject and bind the second interceptor
SecondInterceptor SecondInterceptor = new SecondInterceptor ();
requestInjection(firstInterceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AfterReturning.class),
SecondInterceptor);
}
}
Edit
Look at what you're doing.
You're telling Guice to wrap a method with #AfterReturn with the FirstInterceptor
Then you're calling interceptor.firstCall()
First call does not have #AfterReturn annotation, so why would it be matched against that configuration?
I'm guessing if you called:
intercept.loadParam();
you would see the invoke method. Also, this is great for a test, but in real life you want to have a Service level class have the #AfterReturn which is then Injected into another Api/Job/Etc that will call LoadParam.
edit
Oh no. Take a look at this line
bindInterceptor(Matchers.any(), // a class with this matcher
Matchers.annotatedWith(AfterReturning.class), // a method with this
firstInterceptor);
This means that the injector only fires on the loadParams. You need to annotate the method of the class youw ish to cause the interception with #AfterReturning. And you want the loadParams to be the invoke method.

Convert automatically into a centralized bean for multiple domain objects

I am creating a project which will respond to collect multiple bean object, save it to the database and return the status of the transaction. There can be multiple objects that can be sent from the client. For each object, they are having separate database thus separate controller.
So I planned to create a framework that can accept multiple objects from multiple controllers and send only one centralized object. But I am not sure how to use a centralized object as a return type in the controller(currently I returned them as Object). Below is my code:
Controller:
#RestController
#RequestMapping("/stat/player")
public class PlayerController {
#Autowired
private StatService<PlayerValue> statPlayer;
#RequestMapping("/number/{number}")
public Object findByNumber(#PathVariable String number) { // Here returning Object seem odd
return statPlayer.findByNumber(number);
}
}
Service:
#Service
#Transactional(isolation = Isolation.READ_COMMITTED)
public class PlayerServiceImpl implements StatService<PlayerValue> {
#Autowired
private PlayerRepository repository;
#Override
public PlayerValue findByNumber(String number) {
Optional<PlayerEntity> numberValue = repository.findByNumber(number);
return numberValue.map(PlayerEntity::toValue).orElse(null);
}
}
In service I returned the PlayerValue object but I want to wrap this object into a centralized bean ResponseValue. I created an aspect for that
#Aspect
#Component
public class Converter {
private static final Logger LOG = LoggerFactory.getLogger(Converter.class);
#Pointcut("within(#org.springframework.web.bind.annotation.RestController *)")
public void restControllerClassMethod() {}
private <T> ResponseValue<T> convert(List<T> results) {
String message = results.isEmpty() ? "No result found" : ResponseValueStatus.OK.toString();
return new ResponseValue<>(ResponseValueStatus.OK, message, results);
}
#Around("restControllerClassMethod()")
#SuppressWarnings("unchecked")
public <T> ResponseValue<T> convert(ProceedingJoinPoint joinPoint) {
ResponseValue value;
try {
Object findObject = joinPoint.proceed();
List<Object> objects = toList(findObject);
value = convert(objects);
} catch (NullPointerException e) {
throw new StatException(String.format("Exception thrown from %s from %s method with parameter %s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), joinPoint.getArgs()[0].toString()));
//this exception will go in a controller advice and create a response value with this message
} catch (Throwable e) {
LOG.error("Exception occurred while converting the object", e);
throw new StatException(String.format("Exception thrown from %s from %s method with parameter %s with exception message %s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), joinPoint.getArgs()[0].toString(), e.getMessage()));
}
return value;
}
private List<Object> toList(Object findObject) {
List<Object> objects = new ArrayList<>();
if (findObject instanceof List) {
((List) findObject).forEach(item -> objects.add(findObject));
} else {
objects.add(findObject);
}
return objects;
}
}
To sum up, There could be multiple entity similar to PlayerValue. I need a way to return the result in a centralized bean. Above process work, BUT for this I have to give return type as Object in Controller. Does anybody has an idea how can I use return type as List or T in controller. Also I know it can be done by implementing a ValueConverter interface, but this conversion is straightforward. So it would be nice if any other developer don't have to implement the ValueConverter everytime he want to add a different controller.
Also feel free to review the implementation and let me know if anyone has some alternative idea or some comments.
Note: I reduce a lot of code in the question so that it can be easier to understandable without understanding the actual requirement context. Please do let me know if anyone need more info.
After some research I came across to a better design solution for the framework (but of course with flaws) to achieve conversion to a centralized bean for multiple domain objects is to use a marker interface.
Marker interface can provide a centralized type for all the bean. The main rule need to be followed by the client is to implement that marker interface. So the basic solution is
Marker interface:
public interface StateResponseValue<T> {
}
Implement the interface in all the bean.
public class PlayerValue implements StateResponseValue<PlayerValue> {
}
public class ResponseValue<T> implements StateResponseValue<T> {
//fields and their getter and setter
}
Change the return type in service and controller.
public interface StatService<T> {
StateResponseValue<T> findByNumber(String number);
}
Change the return type in controller
#RestController
#RequestMapping("/stat/player")
public class PlayerController {
#Autowired
private StatService<PlayerValue> statPlayer;
#RequestMapping("/number/{number}")
public StateResponseValue<T> findByNumber(#PathVariable String number) { // Here returning Object seem odd
return statPlayer.findByNumber(number);
}
}
Note: The main drawback I feel is that whenever we want to access the field client need to explicitly cast the object to ResponseValue which is still pretty ugly.
What if you create an AbstractStatController which is generic ?
Generic interface StatService:
public interface StatService<T> {
T findByNumber(String number);
}
Generic abstract class AbstractStatController:
public abstract class AbstractStatController<T> {
abstract StatService<T> getStatService();
#RequestMapping("/number/{number}")
public T findByNumber(#PathVariable String number) {
return getStatService().findByNumber(number);
}
}
Concrete class PlayerController:
#RestController
#RequestMapping("/stat/player")
public class PlayerController extends AbstractStatController<Player> {
private final PlayerService playerService;
public PlayerController(PlayerService playerService) {
this.playerService = playerService;
}
#Override
StatService<Player> getStatService() {
return playerService;
}
}

Design pattern: avoid switch to decide which service call

For a project, we have a Controller/Service/DAO architecture. We implement calls to different providers' APIs so we ended up with some boilerplate code like this in every controller class:
enum {
PARTNER_A, PARTNER_B, PARTNER_C
}
public class MyController {
#Resource PartnerASearchService partnerASearchService;
#Resource PartnerBSearchService partnerBSearchService;
#Resource PartnerCSearchService partnerCSearchService;
public search(InputForm form) {
switch(form.getPartnerName()) {
case PARTNER_A: partnerASearchService.search();
break;
case PARTNER_B: partnerBSearchService.search();
break;
case PARTNER_C: partnerCSearchService.search();
break;
}
}
public otherMethod(InputForm form) {
switch(form.getProvider()) {
case PARTNER_A: partnerAOtherService.otherMethod();
break;
case PARTNER_B: partnerBOtherService.otherMethod();
break;
case PARTNER_C: partnerCOtherService.otherMethod();
break;
}
}
}
Which design pattern can I use to get rid of this switch in every controller? I would prefer the code to be something like the below:
public class MyController {
#Resource ServiceStrategy serviceStrategy;
public search(InputForm form){
serviceStrategy.search(form.getPartnerName())
// or
serviceStrategy.invoke(SEARCH, form.getPartnerName())
}
public otherMethod(InputForm form){
serviceStrategy.other(form.getPartnerName())
// or
serviceStrategy.invoke(OTHER, form.getPartnerName())
}
}
letting the serviceStrategy decide which service implementation to be called, and thus having the partner's switch in a single place.
I've used the term "strategy" because I've been told this design pattern could make it, but I'm not sure of the best way to use it or if there is a better approach to solve this problem.
EDIT: I've updated the question as the term provider is misleading. What I have in the input form is the name of the partner for which we do the request. I want a pattern that decides which is the correct implementation (which one of the several services) to use based on the partner's name in the form
Generally, the form shouldn't need any knowledge of what "provider" is going to handle it. Instead, the providers should be able to explain which kinds of inputs they can handle.
I recommend using a form of Chain of Responsibility (incorporating the refactoring Replace Conditional with Polymorphism) that looks something like this (Groovy for simplicity):
interface ProviderService {
boolean accepts(InputForm form)
void invoke(String foo, InputForm form)
void other(InputForm form)
}
Each implementation of ProviderService implements accepts to indicate whether it can handle a particular form, and your controller stores a List<ProviderService> services instead of individual references. Then, when you need to process a form, you can use:
ProviderService service = services.find { it.accepts(form) }
// error handling if no service found
service.other(form)
See the Spring conversion service for a comprehensive example of this pattern that's used in a major framework.
First remove the duplication of the provider lookup code by extracting it to an own method.
public class MyController {
#Resource
ProviderService searchServiceProvider1;
#Resource
ProviderService searchServiceProvider2;
#Resource
ProviderService searchServiceProvider3;
public void search(InputForm form) {
String provider = form.getProvider();
ProviderService providerService = lookupServiceProvider(provider);
providerService.search();
}
public void other(InputForm form) {
String provider = form.getProvider();
ProviderService providerService = lookupServiceProvider(provider);
providerService.other();
}
private ProviderService lookupServiceProvider(String provider) {
ProviderService targetService;
switch (provider) {
case PROVIDER_1:
targetService = searchServiceProvider1;
break;
case PROVIDER_2:
targetService = searchServiceProvider2;
break;
case PROVIDER_3:
targetService = searchServiceProvider3;
break;
default:
throw new IllegalStateException("No Such Service Provider");
}
return targetService;
}
}
At least you can improve the lookupServiceProvider method and use a map to avoid the switch.
private Map<String, ProviderService> providerLookupTable;
private Map<String, ProviderService> getProviderLookupTable(){
if(providerLookupTable == null){
providerLookupTable = new HashMap<String, ProviderService>();
providerLookupTable.put(PROVIDER_1, searchServiceProvider1);
providerLookupTable.put(PROVIDER_2, searchServiceProvider2);
providerLookupTable.put(PROVIDER_3, searchServiceProvider3);
}
return providerLookupTable;
}
private ProviderService lookupServiceProvider(String provider) {
Map<String, ProviderService> providerLookupTable = getProviderLookupTable();
ProviderService targetService = providerLookupTable.get(provider);
if(targetService == null){
throw new IllegalStateException("No Such Service Provider");
}
return targetService;
}
Finally you will recognize that you can introduce a ProviderServiceLocator, move the lookup logic to this class and let MyController use the ProvicerServiceLocator.
A detailed explanation and example code about service provider interfaces and service provider lookup with standard java can be found in my blog A plug-in architecture implemented with java.
Indeed, you can use the Strategy pattern here. It will look like something like this.
Here, you have to get the designated ServiceProvider from InputForm.
You can have StrategyMaker class something like this.
Public class StrategyMaker{
public SeriveProvider getProviderStrategy(InputForm inputForm){
return inputForm.getProvider();
}
}
And inside controllers you can do something like this.
public class MyController{
StrategyMaker strategyMaker;
public search(InputForm form){
strategyMaker.getProviderStategy(form).search();
}
}
This will be an ideal solution, if you know list of all the provider strategies forehand. Strategy pattern unable to keep Open-Close-Princple when the list is continuously growing.
And one other thing is when you refer a pattern, always try to get the big picture. Don't rigidly look into the implementation example any source provides. Always remember that it's an implementation, not the implementation.
One possible solution when the Partners are not frequently changing:
class ServiceFactory {
#Resource PartnerService partnerASearchService;
#Resource PartnerService partnerBSearchService;
#Resource PartnerService partnerCSearchService;
public static PartnerService getService(String partnerName){
switch(partnerName) {
case PARTNER_A: return partnerASearchService;
case PARTNER_B: return partnerBSearchService;
case PARTNER_C: return partnerCSearchService;
}
}
public class MyController {
#Resource ServiceFactory serviceFactory;
public search(InputForm form) {
serviceFactory.getService(form.getProvider()).search()
}
public otherMethod(InputForm form) {
serviceFactory.getService(form.getProvider()).otherMethod()
}
}
Mixing ideas from different answers I came up to
ServiceProvider.java A superclass for all the service providers. Contains a map of the different services for each partner
public abstract class ServiceProvider implements IServiceProvider {
private final Map<ServiceType, IService> serviceMap;
protected ServiceProvider() {
this.serviceMap = new HashMap<>(0);
}
protected void addService(ServiceType serviceType, IService service) {
serviceMap.put(serviceType, service);
}
public IService getService(ServiceType servicetype, PartnerType partnerType) throws ServiceNotImplementedException {
try {
return this.serviceMap.get(serviceType);
} catch (Exception e) {
throw new ServiceNotImplementedException("Not implemented");
}
}
}
ServiceProviderPartnerA.java there is a service provider for each partner, which are injected with the actual service classes for the different methods.
#Service("serviceProviderPartnerA")
public class ServiceProviderPartnerA extends ServiceProvider {
#Resource(name = "partnerASearchService")
private ISearchService partnerASearchService;
#Resource(name = "partnerABookingService")
private IBookingService partnerABookingService;
#PostConstruct
public void init() {
super.addService(ServiceType.SEARCH, partnerASearchService);
super.addService(ServiceType.BOOKING, partnerABookingService);
}
}
ServiceStrategy.java Injected with the different partners' service providers, it implements the only switch needed in the code and returns the correct service for the correct partner to be used in the controller
#Service("serviceStrategy")
public class ServiceStrategy implements IServiceStrategy {
#Resource(name = "serviceProviderPartnerA")
IServiceProvider serviceProviderPartnerA;
#Resource(name = "serviceProviderPartnerB")
IServiceProvider serviceProviderPartnerB;
#Resource(name = "serviceProviderPartnerC")
IServiceProvider serviceProviderPartnerC;
public IService getService(ServiceType serviceType, PartnerType partnerType) throws PartnerNotImplementedException {
switch (partnerType) {
case PARTNER_A:
return serviceProviderPartnerA.getService(serviceType, partnerType);
case PARTNER_B:
return serviceProviderPartnerB.getService(serviceType, partnerType);
case PARTNER_C:
return serviceProviderPartnerC.getService(serviceType, partnerType);
default:
throw new PartnerNotImplementedException();
}
}
}
SearchController.java finally, in my controllers, I just need to inject the serviceStrategy class and use it to recover the correct service.
#Resource(name = "serviceStrategy")
IServiceStrategy serviceStrategy;
#RequestMapping(value = "/search", method = RequestMethod.GET, produces = "text/html")
#ResponseBody
public String search(#RequestParam(value = "partner", required = true) String partnerType, String... params) {
ISearchService service = (ISearchService) serviceStrategy.getService(ServiceType.SEARCH, partnerType);
return service.search(params);
}
So, switch off! Hope this helps someone

Spring - autowiring with some condition

In my Spring MVC application I have a 'DrawingController' that accepts MultipartHttpRequests from clients.
A user can upload any type of drawing( for the time being only auto cad and bim drawings) from the front end.
There is an interface called 'DrawingService' and two implementations 'BIMDrawingService' and 'CADDrawingService' as follows.
public interface DrawingService{
public String manageUpload();
}
#Component("bimService")
public class BIMDrawingService implements DrawingService{
public String manageUpload() {//}
}
#Component("cadService")
public class CADDrawingService implements DrawingService{
public String manageUpload() {//}
}
public class DrawingController {
#Autowired
#Qualifier("bimService")
private DrawingService bimService;
#Autowired
#Qualifier("cadService")
private DrawingService cadService;
public void setDrawingService(DrawingService bimService) {
this.bimService= bimService;
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String handleFileUpload(MultipartHttpServletRequest request){
//if request type == BIM, then ignore the logic how I differentiate
if bimrequest
bimService.manageupload()
else if cadrequest
cadService.manageupload()
}
I feel this is not the good way to do and my question is how I can inject the services dynamically at run time, even If I add new drawing services later, with the minimal changes I should be able to progress. Please suggest me some best design solution.

Play! - how to reuse common logic for path fragment

I am currently using Play 2.3 and I have to deal with similar URL mappings:
GET /api/companyId/employeeId/tasks
GET /api/companyId/employeeId/timesheets
etc.
In every GET I need to perform similar logic:
public Promise<Result> getEmployeeTimesheets(Long companyId, Long employeeId) {
return promise(() -> {
if (!companyRepository.one(companyId).isPresent()) {
return notFound("Company doesn't exist");
}
if (!employeeRepository.one(employeeId).isPresent()) {
return notFound("Employee doesn't exist");
}
if (!employeeRepository.employeeWorksForCompany(companyId, employeeId)) {
return forbidden("Employee doesn't work for this company");
}
// some actual logic here
});
}
This code repeats over and over again. So far I used plain old inheritance and moved that repeating code into the parent controller class. It gets the job done, but it certainly isn't perfect solution (because I have to invoke parent method and inspect results manually in every controller action).
Is there some more declarative approach in Play that would automatically handle fragment of URL (/api/companyId/employeeId in our case) and either delegate the execution to an appropriate controller, or return an error response (for example 404 - Not Found).
You said you are calling the method again and again in each controller function instead you can use #With annotation.For ex
create a class CheckUrl.java
public class CheckUrl extends play.mvc.Action.Simple {
public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
String host = request().uri();
if (condition one satisfied) {
return F.Promise.pure(redirect("/someurl"));
}else if (condition two satisfied){
return F.Promise.pure(redirect(controllers.routes.SomeController.index()));
}
}
Place #With(CheckUrl.class) in class to apply to all its function.
#With(CheckUrl.class)
public class MyController extends Controller {
}
and for a particular function
public class MyController extends Controller {
#With(CheckUrl.class)
public static Result index() {
}
}
In the above cases CheckUrl.java is invoked before function in a controller

Categories

Resources