JAX-RS filters calling sequence - jaxb

My implemention of the JAX-RS Filters as as follows,
The request filter is :
public class AuthorizationRequestFilter implements ContainerRequestFilter {
public static long entryTime;
#Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
/*some preprocessing before unmarshalling*/
}
}
the Response filter is:-
public class ResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
if (!requestContext.getMethod().equalsIgnoreCase("Head")) {
/*Some processing after Marshalling*/
}
}
my handler is :-
#POST
#Path("abc")
#Produces(MediaType.APPLICATION_XML)
public Response createABC(App app){
/*lines of code*/
return Response.status(Status.CRETED).entity(abc).build();
}
My question is are the filters called after Marshallling and Unmarshalling,i.e is the app object created after the method AuthorizationRequestFilter and abc is Marshalled before calling of Response Filter

The request filter is called before unmarshalling. This should be apparent, as you still have access to the entity input stream (meaning it hasn't been read from yet). You could easily test this by writing a trivial MessageBodyReader. Set an arbitrary header in the request filter, then you will be able to extract the same header from the readers readFrom method.
The response filter will be called before the marshalling. Again this could easily be tested by writing a trivial MessageBodyWriter. Set an arbitrary header in the filter, and you should be able to access it in the writer's writeTo method.
If you want to perform some operation after marshalling, you instead could use a WriterInterceptor, which wraps the call the writer's marshalling method. For example
#Provider
public class SimpleIntercetor implements WriterInterceptor{
#Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
// Processing before marshalling
context.proceed(); // marshal
// Processing after marshalling
}
}
Some Resources:
How to Write Custom Entity Providers
Interceptors
The links are to Jersey documentation, but interceptors, readers, writers are standard to JAX-RS 2.0, so the documentation should be applicable to whatever implementation you're using (for the most part :-)

Related

spring: share value between annotated beans like jsf applicationscope

I am working on a project with jsf 2.2 on the web side and spring 4 on the business side. I have a web filter which receives a parameter from the request url. From this parameter I have to connect to a database. There are cases where there are different databases possible, so depending on the parameter I have to initiate a different database connection. The web filter looks like this:
#Component
public final class SecurityFilter implements Filter
{
#Autowired
private CommonEao commonEao;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest)request;
String instance = req.getParameter("instance");
//I would like to have something here like:
// springContext.addParameter("instance", instance);
String company = req.getParameter("company");
commonEao.getConfiguration(company);
... Do stuff
}
}
How does it works? The commonEao contains methods to make queries to the database (JPA/Eclipselink...). At initialization, no entityManager is present in commonEao since it is injected in SecurityFilter before the doFilter is executed when an url is requested. After the url is requested, the instance of the database to use is known through the 'instance' request parameter.
When the method commonEao.getConfiguration(company) is invoked, the first thing that should happen is to create an entity Manager:
#Repository
public final class CommonEao extends AbstractEao
{
public final void getConfiguration(final String company)
{
if (entityManager == null)
{
//I would like to have something here like:
// String instance = springContext.getParameter("instance");
createEntityManager(instance);
}
else ...
}
}
As you can see, when the first time the url is requested, no entityManager exists and it needs to be created based on the instance name provided by the request. Based on the instance name the properties files containing database connection parameters will be used the call the Persistence.createEntityManagerFactory functionality... etc etc... :)
What is the idea? The idea that I had, as you can see in my comments, is to put a parameter in some global context/container that is available for all Spring beans. This idea comes from the JSF world, where you can create a managed bean, annotate it with applicationscope, define a variable in it, and access this variable from any jsf managed bean through injecting the application scoped bean with the managedproperty annotation:
#ManagedBean
public final class SomeJsfBean
{
#ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
private void method()
{
applicationBean.setInstanceName("instance");
}
}
#ManagedBean
public final class AnotherJsfBean
{
#ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
private void method()
{
String instance = applicationBean.getInstanceName();
}
}
I have some restrictions though. I want to use a global object of Spring. I don't have any XML config in my project. Spring is configured like this and nothing more:
#Configuration
#ComponentScan(value = { "megan.fox.is.hot", "as.is.lindsay.lohan" })
public class SpringConfiguration
{
}
I have looked in many places, something I found was fetching a property from PropertyPlaceholderConfigurer and stuff like that, but I didn't understand how it works and mainly it looks way too complex for what i need: just sharing one variable.
There must be an easy solution like in the JSF world, but i suspect i am looking for the wrong name in the Spring world! :)
Any help is greatly appreciated, this is the last thing I need to fix in my project!

Powermock to mock instance methods called from other executing methods

In this code, i have mocked the one of the ValidateHandlerSoapClient class method which is instantiated and called this method (soapClientSpy.processSoapRequestRespons) in validateMsisdnHandlerIRSpy.validate().So soapClientSpy.processSoapRequestResponse is not working , instead the real method is called.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ValidateMsisdnHandler.class,ValidateHandlerSoapClient.class})
public class Demo {
MessageControl messageControl=PowerMockito.mock(MessageControl.class);
Validate validate=PowerMockito.mock(Validate.class);
ValidateMsisdnHandlerIR validateMsisdnHandlerIRSpy = PowerMockito.spy(new ValidateMsisdnHandlerIR());
ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient());
#Before
public void initialize() throws Exception
{
PowerMockito.when(validate.getAccountId()).thenReturn("0879221485");
PowerMockito.doReturn(true).when(validateMsisdnHandlerIRSpy, "isPrePaid",anyString());
MemberModifier.field( ValidateMsisdnHandlerIR.class, "endDate").set(
validateMsisdnHandlerIRSpy, "10-FEB-2015");
PowerMockito.when(soapClientSpy.processSoapRequestResponse(anyString())).thenReturn(true);
PowerMockito.whenNew(ValidateHandlerSoapClient.class).withNoArguments().thenReturn(soapClientSpy);
}
#Test
public void testValidateMsisdn_Cr6_Roverprempay_Not_Roverpayg() throws Exception{
Response response = validateMsisdnHandlerIRSpy.validate(validate,messageControl);
}
Replace
ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient())
with
ValidateHandlerSoapClient soapClientMock = PowerMockito.mock(ValidateHandlerSoapClient.class)
A spy by default just calls the methods of the underlying regular class. What you want to do is (presumably) nothing when the methods of the soap client are called.
Then of course you will need to make also change:
PowerMockito.whenNew(ValidateHandlerSoapClient.class).withNoArguments().thenReturn(soapClientMock);

Spring Integration - Annotation for HeaderValueRouter

How can I annotate a method so it processes messages for a specific header value? I already have a HeaderValueRouter in XML config that routes to the appropriate class and executes the correct method based on the payload type. I would like to annotate some methods in this class (specifically with no parameters) like this:
#Router(header("operation")="one")
public String getOne() {}
#Router(header("operation")="two")
public String getTwo() {}
The point of this is to enable a REST like service where the user can call a URL like ../service/one, and Spring Integration will set the operation header to "one". Basically I want to have the ability to quickly add methods to my web service and they automatically work by adding the above annotations to my underlying service.
There is no such mechanism. Even if it looks interest I'm not sure that we should introduce that -it breaks some messaging concerns
Anyway with XML you have <header-value-router>, which has a channel-mapping. That one specifies where to send the message to invoke appropriate service-activator.
So, I suggest you do the same using annotations:
#MessagingGateway(defaultRequestChannel = "routerChannel")
public interface ServiceGateway {
Object invoke(String operation);
}
....
#Autowired
private ServiceGateway serviceGateway;
#RequestMapping("/service/{operation}")
public Object operation(#PathVariable String operation) {
return this.serviceGateway.invoke(operation);
}
#Router(inputChannel = "routerChannel")
public String route(String operation) {
return operation;
}
...
#ServiceActivator(inputChannel = "one")
public String getOne() {}
...
#ServiceActivator(inputChannel = "two")
public String getTwo() {}

Mockito implemetation for formhandlers in ATG

I am new to Mockito as a concept. Can you please help me understand using Mockito for formhandlers in ATG. Some examples will be appreciated.
There is a good answer (related to ATG) for other similar question: using-mockito-for-writing-atg-test-case. Please review if it includes what you need.
Many of ATG-specific components (and form handlers particularly) are known to be "less testable" (in comparison to components developed using TDD/BDD approach), b/c design of OOTB components (including reference application) doesn't always adhere to the principle of having "Low Coupling and High Cohesion"
But still the generic approach is applicable for writing unit-tests for all ATG components.
Below is a framework we've used for testing ATG FormHandlers with Mockito. Obviously you'll need to put in all the proper bits of the test but this should get you started.
public class AcmeFormHandlerTest {
#Spy #InjectMocks private AcmeFormHandler testObj;
#Mock private Validator<AcmeInterface> acmeValidatorMock;
#Mock private DynamoHttpServletRequest requestMock;
#Mock private DynamoHttpServletResponse responseMock;
private static final String ERROR1_KEY = "error1";
private static final String ERROR1_VALUE = "error1value";
#BeforeMethod(groups = { "unit" })
public void setUp() throws Exception {
testObj = new AcmeFormHandler();
initMocks(this);
}
//Test the happy path scenario
#Test(groups = { "unit" })
public void testWithValidData() throws Exception {
testObj.handleUpdate(requestMock, responseMock);
//Assume your formhandler calls a helper method, then ensure the helper method is called once. You verify the working of your helper method as you would do any Unit test
Mockito.verify(testObj).update(Matchers.refEq(requestMock), Matchers.refEq(responseMock), Mockito.anyString(), (AcmeBean) Mockito.anyObject());
}
//Test a validation exception
#Test(groups = { "unit" })
public void testWithInvalidData() throws Exception {
Map<String, String> validationMessages = new HashMap<String, String>();
validationMessages.put(ERROR1_KEY, ERROR1_VALUE);
when(acmeValidatorMock.validate((AcmeInterface) Mockito.any())).thenReturn(validationMessages);
testObj.handleUpdate(requestMock, responseMock);
assertEquals(1, testObj.getFormExceptions().size());
DropletFormException exception = (DropletFormException) testObj.getFormExceptions().get(0);
Assert.assertEquals(exception.getMessage(), ERROR1_VALUE);
}
//Test a runtime exception
#Test(groups = { "unit" })
public void testWithRunProcessException() throws Exception {
doThrow(new RunProcessException("")).when(testObj).update(Matchers.refEq(requestMock), Matchers.refEq(responseMock), Mockito.anyString(), (AcmeBean) Mockito.anyObject());
testObj.handleAddGiftCardToCart(requestMock, responseMock);
assertEquals(1, testObj.getFormExceptions().size());
DropletFormException exception = (DropletFormException) testObj.getFormExceptions().get(0);
Assert.assertEquals(exception.getMessage(), GENERAL_ERROR_KEY);
}
}
Obviously the above is just a framework that fit in nicely with the way in which we developed our FormHandlers. You can also add validation for redirects and stuff like that if you choose:
Mockito.verify(responseMock, Mockito.times(1)).sendLocalRedirect(SUCCESS_URL, requestMock);
Ultimately the caveats of testing other people's code still applies.
Here's what I do when I unit test a form handler (at least until I manage to release a major update for AtgDust). Note that I don't use wildcard imports, so I'm not sure if this causes any namespace conflicts.
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.*;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import atg.servlet.*;
import some.form.handler.FormHandler;
#RunWith(JUnit4.class)
public class FormHandlerTest {
#Mock DynamoHttpServletRequest request;
#Mock DynamoHttpServletResponse response;
FormHandler handler;
#Before
public void setup() {
initMocks(this);
handler = new FormHandler();
}
#Test
public void testSubmitHandlerRedirects() {
handler.handleSubmit(request, response);
verify(response).sendLocalRedirect(eq("/success.jsp"), eq(request));
assertThat(handler.getFormError(), is(false));
}
}
The basic idea is to set up custom behavior for mocks/stubs using when() on the mock object method invocation to return some test value or throw an exception, then verify() mock objects were invoked an exact number of times (in the default case, once), and do any assertions on data that's been changed in the form handler. Essentially, you'll want to use when() to emulate any sort of method calls that need to return other mock objects. When do you need to do this? The easiest way to tell is when you get NPEs or other runtime exceptions due to working with nulls, zeros, empty strings, etc.
In an integration test, ideally, you'd be able to use a sort of in-between mock/test servlet that pretends to work like a full application server that performs minimal request/session/global scope management. This is a good use for Arquillian as far as I know, but I haven't gotten around to trying that out yet.

Catching exceptions with servicestack

We have been using ServiceStack for REST based services for a while now and so far it has been amazing.
All of our services have been written as:
public class MyRestService : RestService<RestServiceDto>
{
public override object OnGet(RestServiceDto request)
{
}
}
For each DTO we have Response equivalent object:
public class RestServiceDto
{
public ResponseStatus ResponseStatus {get;set;}
}
which handles all the exceptions should they get thrown.
What I noticed is if an exception is thrown in the OnGet() or OnPost() methods, then the http status description contains the name of the exception class where as if I threw a:
new HttpError(HttpStatus.NotFound, "Some Message");
then the http status description contains the text "Some Message".
Since some of the rest services are throwing exceptions and others are throwing new HttpError(), I was wondering if there was a way without changing all my REST services to catch any exceptions and throw a new HttpError()?
So for example, if the OnGet() method throws an exception, then catch it and throw a new HttpError()?
Using Old API - inherit a custom base class
As you're using the old API to handle exceptions generically you should provide a Custom Base class and override the HandleException method, e.g:
public class MyRestServiceBase<TRequest> : RestService<TRequest>
{
public override object HandleException(TRequest request, Exception ex)
{
...
return new HttpError(..);
}
}
Then to take advantage of the custom Error handling have all your services inherit your class instead, e.g:
public class MyRestService : MyRestServiceBase<RestServiceDto>
{
public override object OnGet(RestServiceDto request)
{
}
}
Using New API - use a ServiceRunner
Otherwise if you're using ServiceStack's improved New API then you don't need to have all services inherit a base class, instead you can just tell ServiceStack to use a custom runner in your AppHost by overriding CreateServiceRunner:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(
ActionContext actionContext)
{
return new MyServiceRunner<TRequest>(this, actionContext);
}
Where MyServiceRunner is just a just custom class implementing the custom hooks you're interested in, e.g:
public class MyServiceRunner<T> : ServiceRunner<T> {
public override object HandleException(IRequestContext requestContext,
TRequest request, Exception ex) {
// Called whenever an exception is thrown in your Services Action
}
}

Resources