Method interception or validation of request params in Sitebricks controller
Asked Answered
M

1

6

I'm using Sitebricks with Guice to implement REST service and I have a set of methods like this:

@Get
@At("/:version/har/mostRecentEntry/assertResponseTimeWithin")
public Reply<?> doSomething(@Named("version") int version, Request<String> request) {
// Validation logic for request parameters ...

// Extracting parameters (converting url params to domain area objects)

// Actual business logic
}

Which leads to a lot of copy/pasted code.

I'm looking for some way to separate common validating & extracting data logic from request parameters. Probably I can use AOP to do it, but maybe there's easier way Sitebricks provides?

Mindful answered 20/3, 2019 at 7:54 Comment(0)
C
5

A few considerations:

  • Google's Sitebricks project is dead
  • official site is down (sitebricks.org)
  • last Github commit - 2015

My recommendation is to not build anything with that framework.

You should definitely consider alternatives for implementing REST services (e.g. SpringBoot).

maybe there's easier way Sitebricks provides?

That being said, Sitebricks doesn't seem to offer validation out of the box.

The code you can find related to validation in Sitebrick is:

@ImplementedBy(AlwaysValidationValidator.class)
public interface SitebricksValidator {

    Set<? extends ConstraintViolation<?>> validate(Object object);

}

and this:

public class AlwaysValidationValidator implements SitebricksValidator {

    @Override
    public Set<? extends ConstraintViolation<?>> validate(Object object) {
        return null; //unfinished
    }

}

This is unfinished implementation!

Your best option is to use javax validation in a standalone setup. This includes hibernate-validator + javax expression language - reference implementation of JSR 380. It has a lot of build in constraints (e.g. @NotNull, @Size etc.) and is extensible - you can create your own constraints implementing the right interfaces (the AOP part is handled by the framework).

A more simple alternative is Guava's PreConditions.

Cuirassier answered 29/3, 2019 at 10:44 Comment(2)
Thank you, the considerations make perfect sense, if only I had chance to get rid of sitebricks.Mindful
You're welcome, but if you have to stick to Sitebricks, you can see the validation implementation is unfinished. You need to opt in using some framework (e.g. as I have suggested javax.validation - JSR 380), which does leverage AOP or do you your own implementation using something else.Cuirassier

© 2022 - 2024 — McMap. All rights reserved.