Form Param are not receiving with jersey , Weblogic 12 c - web-services

I have my own custom context which contain relevant data required by the jersey service
public class TangoContextRC extends ResourceConfig {
public TangoContextRC() {
register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(TangoContextProvider.class).to(TangoContext.class);
}
});
}
}
code for TangoContextProvider is
public class TangoContextProvider implements Factory<TangoContext> {
private final HttpServletRequest request;
#Inject
public TangoContextProvider(HttpServletRequest request) {
this.request = request;
}
#Override
public TangoContext provide() {
return TangoContextFactory.getInstance(request);
}
#Override
public void dispose(TangoContext t) {
}
}
Main problem is in tomcat all form params are correctly receiving and working fine but in weblogic version 12 c form params are receiving as null.
code for service is
#POST
#Path("{ruleObjectType}/ruleObject")
#Produces("application/json")
public String getRuleObject(#Context TangoContext tangoContext,
#FormParam("ruleData") String ruleData,
#PathParam("ruleObjectType") String ruleObjectType){
//some logic here
}
why form params are not receiving in weblogic?
but i accidentally change position of #Context tangoContext to last parameter is start receiving all form params in weblogic as well as tomcat.
Please tell me what is the reason behind this what is key role of this #Context TangoContext as a last parameter?

Related

How to Unit testing in CQRS Pattern C#

I need to know how to Unit testing in CQRS pattern. as a beginer i dont have much idea about that. I develope below Command and queries. I need to Test those
Here is my add student command
public record AddStudentCommand(Student student):IRequest<Student>;
Hear is my Add Studnet Hadler
public class AddStudentHandler : IRequestHandler<AddStudentCommand, Student>
{
private readonly appDbContext _context;
public AddStudentHandler(appDbContext context)
{
_context = context;
}
public async Task<Student> Handle(AddStudentCommand request, CancellationToken cancellationToken)
{
_context.students.Add(request.student);
await _context.SaveChangesAsync();
return request.student;
}
}
This is Get All Student Query
public record GetAllStudentDataQuery : IRequest<IEnumerable<Student>>;
This is my Get All Student Handler
public class GetAllStudentHandler : IRequestHandler<GetAllStudentDataQuery, IEnumerable<Student>>
{
private readonly appDbContext _context;
public GetAllStudentHandler(appDbContext context)
{
_context = context;
}
public async Task<IEnumerable<Student>> Handle(GetAllStudentDataQuery request, CancellationToken cancellationToken)
{
return _context.students;
}
}
I need to Unit test these methods.
it doesn't matter design patterns. you need to learn
-What is unit testing_
-Which framework you should use?
You should start with https://xunit.net/docs/getting-started/netfx/visual-studio

Unit testing middleware with NUnit and NSubstitute

I've written a bit of middleware in an ASP.NET Core site and I'm trying to unit test it, mainly by following this guide that uses Moq.
My problem is finding an NUnit/NSubstitute equivalent for new DefaultHttpContext(). Substituting HttpContext will trigger the middleware, but it passes the try. I presume this is because of the issue quoted below. Does NUnit have a function to create a real HttpContext, or am I looking at a lot more infrastructure to achieve this?
I am sending an instance of DefaultHttpContext to the Invoke method. I can't use a mocked HttpContext in this scenario because the first middleware (the lambda function that we passed to the constructor) will need to write to the response. Hence the HttpResponse needs to be a real object not mocked.
Here is the code for my Test
[TestFixture]
public class ExceptionHelperTests
{
private IErrorRepository errorRepository;
private ExceptionHandler handler;
[SetUp]
public void Setup()
{
errorRepository = Substitute.For<IErrorRepository>();
}
[Test]
public async void Given_AnExceptionHappens_Then_ItShouldBeLogged()
{
// Arrange
const string username = "aUser";
var user = Substitute.For<ClaimsPrincipal>();
user.Identity.Name.Returns(username);
handler = new ExceptionHandler(
next: async (innerHttpContext) =>
{
innerHttpContext.User = user;
},
repository: errorRepository);
// Act
await handler.Invoke(new DefaultHttpContext());
// Assert
errorRepository.Received().LogException(Arg.Any<string>(), Arg.Any<Exception>(), Arg.Is(username));
}
}
Here is the IErrorRepository
public interface IErrorRepository
{
Exception LogException(string message, Exception ex, string userId);
void LogMessage(string message, string errorDetail, string userId);
}
And here is the middleware (with a simplified HandleException):
public sealed class ExceptionHandler
{
private readonly RequestDelegate _next;
private readonly IErrorRepository repository;
public ExceptionHandler(RequestDelegate next, IErrorRepository repository)
{
_next = next;
this.repository = repository;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
HandleException(ex, context.User.Identity.Name);
}
}
public void HandleException(Exception ex, string userId)
{
repository.LogException("An unhandled exception has occurred.", ex, userId);
}
}
DefaultHttpContext is just the default implementation of HttpContext abstract class.
You just could do
var HttpContextSub = Substitute.For<HttpContext>();

How to pass superclass object to restful service (jersey)

I have two POJOs
#XmlRootElement
public class PojoBase {
}
#XmlRootElement
public class PojoRequest extends PojoBase {
private String strTemplate;
public void setTemplate(String strTemplate) {
this.strTemplate = strTemplate;
}
public String getTemplate() {
return strTemplate;
}
}
#XmlRootElement
public class PojoResponse extends PojoBase {
private String strName;
public void setName(String strName) {
this.strName = strName;
}
public String getName() {
return strName;
}
}
I have service which accepts the base class and returns the base class as response.
#POST
#Path("/start")
#Produces({MediaType.APPLICATION_JSON})
#Consumes(MediaType.APPLICATION_JSON)
public PojoBase registerNumber(JAXBElement<PojoBase> theRequest) {
//does some work with theRequest.
//here the theRequest object doesn't has pojoRequest data.
PojoResponse pojoResponse = new PojoResponse();
pojoResponse.setName("Sample");
return pojoResponse;
}
From client I am sending pojo base object but not sure why Restful doesn't get actual theRequest object.
Here is the client code:
public class HttpClient {
static String _strServiceURL = "http://127.0.0.1:8080/middleware/rest/service/start";
public static void main(String[] args) throws Exception {
PojoRequest pojoRequest = new PojoRequest();
pojoRequest.setTemplate("Somedata");
PojoBase response = getResponse(pojoRequest);
PojoResponse pojoresponse = (PojoResponse) response;
System.out.println(response);
}
private static PojoBase getResponse(PojoBase request) {
try {
Client client = Client.create();
WebResource webResource = client.resource(_strServiceURL);
ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, request);
System.out.println(response.getStatus());
if(response.getStatus() == 200){
PojoBase response = response.getEntity(PojoBase.class);
return response;
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
Can you please tell me how to get the PojoRequest at Service end?
Any help is appreciated.
Thanks
I don't think you can pass a superclass to jersey like this. I believe, though I may be wrong, that as registerNumber() has a parameter JAXBElement<PojoBase> it will do something like:
instantiate a PojoBase
do reflection on PojoBase (which has no properties), therefore nothing to set.
call registerNumber() with the practically empty PojoBase object
So why not try changing the signature to:
public PojoBase registerNumber(JAXBElement< PojoRequest > theRequest)
or even (with com.sun.jersey.api.json.POJOMappingFeature = true):
public PojoBase registerNumber(PojoRequest theRequest)

How to mock HttpSession in JSF

i have a service method that get session attribute and i want to make unit test for this service method and i was wondering how to mock the HttpSession in jsf.
1- use the FacesContextMocker class:
public abstract class FacesContextMocker extends FacesContext {
private FacesContextMocker() {}
private static final Release RELEASE = new Release();
private static class Release implements Answer<Void> {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
setCurrentInstance(null);
return null;
}
}
public static FacesContext mockFacesContext() {
FacesContext context = Mockito.mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE).when(context).release();
return context;
}
}
2- in the test class #Before method do the following:
FacesContextMocker.mockFacesContext();
ExternalContext externalContext = Mockito.mock(ExternalContext.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext())
.thenReturn(externalContext);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(
FacesContext.getCurrentInstance().getExternalContext()
.getRequest()).thenReturn(request);
HttpSession httpSession = Mockito.mock(HttpSession.class);
Mockito.when(GeneralUtils.getHttpSession()).thenReturn(httpSession);
3- the getHttpSession method is as follows:
public static HttpSession getHttpSession() {
return ((HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest()).getSession();
}
4- in the test method do the following:
Mockito.when(
GeneralUtils.getHttpSession().getAttribute(
"userID")).thenReturn("1");
5- this is assuming that in your service method that you are making the unit test for you have code like:
String currentUserID = (String) GeneralUtils.getHttpSession()
.getAttribute(userID);

Mocking digest authentication in RestEasy

I am using RestEasy to develop a REST server and using the mock dispatcher (org.jboss.resteasy.mockMockDispatcherFactory) for testing the service in my unit tests. My service requires digest authentication and I would to make that part of my testing.
Each of my services accepts a #Context SecurityContext securityContext parameter.
Is there any way is inject a fake SecurityContext in the dispatcher so that I can test that my security methods function properly?
You have to add the SecurityContext into the context data map in ResteasyProviderFactory.
public class SecurityContextTest {
#Path("/")
public static class Service {
#Context
SecurityContext context;
#GET
public String get(){
return context.getAuthenticationScheme();
}
}
public static class FakeSecurityContext extends ServletSecurityContext {
public FakeSecurityContext() {
super(null);
}
#Override
public String getAuthenticationScheme() {
return "unit-test-scheme";
}
}
#Test
public void securityContextTest() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Service());
ResteasyProviderFactory.getContextDataMap().put(SecurityContext.class, new FakeSecurityContext());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals("unit-test-scheme", response.getContentAsString());
}
}
For those coming across this issue today, adding Contexts has been moved from the RestEasyProviderFactory class into the Dispatcher class using getDefaultContextObjects() method.
I've edited the old answer with the new call:
public class SecurityContextTest {
#Path("/")
public static class Service {
#Context
SecurityContext context;
#GET
public String get(){
return context.getAuthenticationScheme();
}
}
public static class FakeSecurityContext extends ServletSecurityContext {
public FakeSecurityContext() {
super(null);
}
#Override
public String getAuthenticationScheme() {
return "unit-test-scheme";
}
}
#Test
public void securityContextTest() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Service());
dispatcher.getDefaultContextObjects().put(SecurityContext.class, new FakeSecurityContext());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals("unit-test-scheme", response.getContentAsString());
}
}