I have implemented a filter as below -
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
#WebFilter("/login.jsf")
public class ServiceFilter implements ContainerRequestFilter, ContainerResponseFilter, Filter {
public ServiceFilter() {}
#PostConstruct
public void init() {
logger.debug("initialized.");
}
#Override
public void destroy() {
logger.debug("destroyed");
}
#Override
public void init(FilterConfig arg0) throws ServletException {
//nothing here
}
...other method overides
}
When I deploy it on Wildfly10, I see the below gets printed
TIMESTAMP DEBUG ServiceFilter:65 - Initialized (ServiceFilter#39df1f0b)
TIMESTAMP DEBUG ServiceFilter:65 - Initialized (ServiceFilter#1a33dd9)
ServiceFilter class is also registered as a root resource in one of the class which implements javax.ws.rs.core.Application. This class acts as an entry point for rest and web resources.
How can I avoid the ServiceFilter class from being initialized twice? Or, is this okay as the filter implements both servlet and rest filters? Or, should I move the implementation in their own class files?
PS: The above stated behavior doesn't actually hinder any functionality offered by my application (I think and could be otherwise) but just wanted to make sure that I'm doing it right.
Related
I have an application based on Jersey JAX-RS. I need to refactor the event handler and therefore also write a test for it.
I'm trying to do this with the JerseyTest Framework. I created a configuration to extend ResourceConfig, but when I use the target () call the handler is not called.
I will present the situation using code.
Here is an example Resource class:
package com.my.page;
import org.glassfish.hk2.api.messaging.Topic;
import com.my.core.entity.Link;
import com.my.core.location.LinkHitLocationFactory;
import com.my.core.service.LinkService;
import com.my.core.service.link.LinkFinder;
import com.my.core.service.link.LinkFinderFactory;
import com.my.event.LinkHitEvent;
import com.my.exception.FragmentNotFoundException;
import javax.annotation.security.PermitAll;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
#PermitAll
#Path("/")
public class LinkResource {
#Inject
private LinkService linkService;
#Inject
private Topic<LinkHitEvent> linkHitPublisher;
#Inject
private LinkFinderFactory linkFinderFactory;
#Inject
private LinkHitLocationFactory linkHitLocationFactory;
#GET
#Path("/{fragment:[^ ]{1,32}}")
public Response redirect(
#PathParam("fragment") String fragment,
#HeaderParam("Range") String range,
#HeaderParam("User-Agent") String userAgent,
#Context HttpHeaders headers) throws Exception {
LinkFinder linkFinder = linkFinderFactory.getLinkFinder(fragment);
Link link = linkFinder.getLink(fragment);
if (link.isExpired()) {
throw new FragmentNotFoundException(fragment);
}
linkService.insertHit();
linkHitPublisher.publish(new LinkHitEvent(link));
return handlerFactory.getHandler(link).handleGet(link, range).build();
}
}
Event test:
package com.my.page;
import org.glassfish.hk2.extras.events.internal.TopicDistributionModule;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.comvision.hk2.events.ThreadedEventDistributorService;
import com.my.client.CallbackTargetBuilder;
import com.my.core.entity.Link;
import com.my.core.mapper.LinkMapper;
import com.my.core.service.LinkService;
import com.my.page.resource.LinkResource;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import static javax.ws.rs.core.Response.Status.TEMPORARY_REDIRECT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
#RunWith(MockitoJUnitRunner.class)
public class CallbackEventTest extends JerseyTest {
#Mock
private LinkMapper linkMapper;
#Mock
private LinkService linkService;
private CallbackTargetBuilder callbackTargetBuilder;
private final String callbackUrl = "";
#Override
protected Application configure() {
this.callbackTargetBuilder = spy(new CallbackTargetBuilder(this.callbackUrl));
ResourceConfig config = new ResourceConfig(LinkResource.class);
config.register(new TopicDistributionModule());
config.register(new AbstractBinder() {
#Override
protected void configure() {
addActiveDescriptor(ThreadedEventDistributorService.class).setRanking(100);
}
});
config.register(new EventsContainerListener(CallbackEventHandler.class));
config.register(new AbstractBinder() {
#Override
protected void configure() {
bind(linkMapper).to(LinkMapper.class);
bind(linkService).to(LinkService.class);
bind(mock(LinkService.class)).to(LinkService.class);
bind("").to(String.class).named("varPath");
bind("127.0.0.1").to(String.class).named("requestIP");
bind(callbackTargetBuilder).to(CallbackTargetBuilder.class);
}
});
return config;
}
#Test
public void publish_event() {
Link link = mock(Link.class);
when(link.getUrl()).thenReturn("example");
when(link.getName()).thenReturn("test");
when(linkMapper.getByName(anyString())).thenReturn(link);
Response response = target("/testY").property("jersey.config.client.followRedirects", false).request().get();
assertEquals(TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
verify(callbackTargetBuilder).build();
}
}
For testing purposes, I only injected callbackTargetBuilder into the handler, and called the build method on it to verify the call:
package com.my.page;
import org.glassfish.hk2.api.messaging.MessageReceiver;
import org.glassfish.hk2.api.messaging.SubscribeTo;
import org.jvnet.hk2.annotations.Service;
import com.my.client.CallbackTargetBuilder;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
#Service
#Singleton
#MessageReceiver
public class CallbackEventHandler {
#Named("callbackUrl")
private String url;
#Inject
private CallbackTargetBuilder callbackTargetBuilder;
#MessageReceiver
public void handle(#SubscribeTo LinkHitEvent event) {
Form form = new Form();
form.param("id", event.getLink().getId().toString());
form.param("name", event.getLink().getName());
callbackTargetBuilder.build();
Client client = ClientBuilder.newClient();
client.target(url).request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
}
}
Edit:
I tried to register dependencies differently, but it does not bring satisfactory results. Each time verification fails:
verify (callbackTargetBuilder) .build ();
Looking for information I found that I can configure the DeploymentContext, but I don't know if this is the right direction.
Edit the second:
A quick test shows that I may have some more basic problem with mocking. Because the call:
verify (linkService) .insertHit (anyObject ());
It also fails.
I will write only for posterity that the above code is correct. The problem was a lot of small bugs in the tested code and how to mock it.
I have a servlet annotated with #WebServlet("*.html") and a controller with #GetMapping("/greeting.html"). Despite the controller mapping being more specific, the servlet takes precedence.
In my application I can't trivially change the mapping of the servlet (I'm in the middle of a complex migration from servlets to Spring-Boot).
I tried #Order annotation, and different matching rules. So far no progress.
You can reproduce it with just 3 classes:
application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
#SpringBootApplication
#ServletComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
GreetingController.java
package hello;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class GreetingController {
#GetMapping("/greeting.html")
#Order(Ordered.HIGHEST_PRECEDENCE)
#ResponseBody
public String greeting() {
return "this is geeting.html";
}
}
SimpleServlet.java
package hello;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
#WebServlet("/*.html")
#Order(Ordered.LOWEST_PRECEDENCE)
public class SimpleServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("This is *.html servlet");
super.doGet(req, resp);
}
}
When accessing localhost:8080 I expect to see this is geeting.html, instead I get This is *.html servlet.
I built a package to give a authentication handler. That engine will be triggered when a method/class as annotated with #Secured so the ContainerRequestFilter will be triggered.
But I'm using this library in another package and when I annoted a method with the #Secured the ContainerRequestFilter` engine is not triggered. So I need help with that.
I tried to import manually with #Inject and #EJB but when I deployed that application in weblogic container I got some errors about dependency.
AuthenticatePackage -
The interceptor:
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
#Secured
#Provider
#Priority(Priorities.AUTHORIZATION)
public class SecurityInterceptor implements ContainerRequestFilter {
#Context private ResourceInfo resourceInfo;
#Inject private JWTService jwtService;
public static final String AUTHENTICATION_SCHEME = "Bearer";
....
The Annotation
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#NameBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Secured {
String[] roles() default {};
}
Package when I use that engine
#GET
#Path("/getSignedUser")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Secured
public Response getSignedUser(#HeaderParam("Authorization") String token) {
UserSchema userSchema = this.authenticationService.getSignedUser(token.substring(SecurityInterceptor.AUTHENTICATION_SCHEME.length()).trim());
return Response.status(Response.Status.OK).entity(userSchema).build();
}
In Spring/Hibernate project, in my entity class I have:
package klab.finance.main.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import klab.backend.entity.postgres.base.BaseEntity;
import klab.backend.utils.DateTimeUtils;
import klab.backend.utils.JsonDateTime;
import klab.backend.utils.json.LocalDateTimeToTimestampDeserializer;
import klab.backend.utils.json.TimestampToLocalDateTimeSerializer;
import org.hibernate.annotations.Where;
import org.joda.time.LocalDateTime;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name="transactions")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Transaction extends BaseEntity {
private Long bankTransactionDate;
#Column(name="bank_transaction_date")
#JsonSerialize(using = TimestampToLocalDateTimeSerializer.class)
public Long getBankTransactionDate(){
return bankTransactionDate;
}
#JsonDeserialize(using = LocalDateTimeToTimestampDeserializer.class)
public void setBankTransactionDate(Long bankTransactionDate){
this.bankTransactionDate=bankTransactionDate;
}
}
My serializer class:
package klab.backend.utils.json;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import klab.backend.entity.postgres.base.BaseEntity;
import klab.backend.utils.DateTimeUtils;
import org.joda.time.LocalDateTime;
import java.io.IOException;
public class TimestampToLocalDateTimeSerializer extends JsonSerializer<Long> {
#Override
public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString("blabla");
}
}
I expect to get JSON with "bank_transaction_date": "blabla".
Instead, I get it with "bank_transaction_date": null. I also notice, that if I set a breakpoint in my serializer, debugger is never stopping there, so it is probably not used.
What's wrong?
The answer was very simple: bankTransactionDate was null, and it turns out, that for null values serializer is not called :)
Once I filled database with values, serializer started to work and gave me "bank_transaction_date": "blabla".
I have the following hierarchy:
#Validated
public class BaseResource
and
public class DeviceResource extends BaseResource
The #Validated annotation is as follows:
package com.redbend.validation.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Scope;
#Scope
#Target(TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Inherited
public #interface Validated {
}
And I have a Spring Aspect with the following advice:
package com.redbend.validation.aspect;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.redbend.exceptions.EExceptionMsgID;
import com.redbend.exceptions.runtime.MissingMandatoryParameterException;
import com.redbend.validation.annotation.MandatoryOneOfParams;
import com.redbend.validation.annotation.MandatoryParams;
import com.redbend.validation.annotation.NotEmpty;
import com.redbend.validation.annotation.OneOfParamsForValue;
import com.redbend.validation.annotation.OneOfParamsForValueMap;
import com.redbend.validation.annotation.ParamsForValue;
import com.redbend.validation.annotation.ParamsForValueMap;
#Aspect
#Component
#Order(2)
public class ValidationInterceptor {
private static Logger logger = LoggerFactory.getLogger(ValidationInterceptor.class);
public ValidationInterceptor() {
// TODO Auto-generated constructor stub
}
#Before("within(com.redbend..*) && #within(com.redbend.validation.annotation.Validated) ")
public void validate(JoinPoint joinPoint) throws Exception {
validateParams(joinPoint);
}
When I call a method in DeviceResource, it is not caught by the aspect, even thought it inherits from BaseResource which is annotated with #Validated, and #Validated is annotated with #Inherited.
When I annotate DeviceResource with #Validated it works fine. How can I make the aspect intercept my method in DeviceResource without annotating it with #Validated?
Thanks,
Amir
within(#com.redbend.validation.annotation.Validated)
is incorrect, it should be
#within(com.redbend.validation.annotation.Validated)
I eventually solved it by changing the pointcut expression in my aspect:
#Before("within(com.redbend..*) && within(#com.redbend.validation.annotation.Validated *)")
I still don't know why it didn't work before or why #within(com.redbend.validation.annotation.Validated)
didn't work...