ContainerRequestContext not being injected into business logic - jax-rs

I am using jaxrs 2.0 & am trying to populate an object in the ContainerRequestContext & retrive it in the business logic.
I am populating the object in the ContainerRequestContext like :
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
MyObject myObject = new MyObject();
requestContext.setProperty("myObject", myObject);
}
And I am trying to read it in the business logic like :
#GET
#Path("/custom")
public String data(#Context ContainerRequestContext crc) {
Object pco = crc.getProperty("myObject");
}
I am using this approach from the example shared in : How to inject an object into jersey request context?
However I am getting the ContainerRequestContext crc as null. Can someone tell me what I could be doing wrong ?

I have tested the exact code asked in the question which works as it is with following setup:
spring-boot-starter-parent: 2.3.4.RELEASE
spring-boot-starter: inherited from parent
spring-boot-starter-jersey: inherited from parent
which evaluates to Spring 5.2.9.RELEASE, Jersey 2.30.1
Arquillian with Jersey can work.

Related

Why is static variable unavailable in controller and how does DI help here

I am porting from traditional mvc to .net core
There is a static class where values are assigned on application start.
public static class WPSGlobalSettings
{
private static readonly string ToolboxDatabaseName = GetValue<string>("tbdatabasename", "db");
public static NpgsqlConnectionStringBuilder ToolboxConnString = build_conn_str(ToolboxDatabaseName);
...
}
However when I try to access it from Controller, it throws exception and is null
public class StatusController : Microsoft.AspNetCore.Mvc.ControllerBase
{
protected StatusDAL status_dal= new StatusDAL(WPSGlobalSettings.ToolboxConnString);
...
}
I want to understand why it stopped working after porting and how does Dependency Injection help here?
Note: I have resolved the issue here but want to clear my concepts.

How to mock a MyBatis mapper method using JMockit

We have a service component (#service) which internally uses MyBatis to do CRUD operations. All the components are managed by Spring.
Lets assume our MyBatis mapper file
class MyBatisMapper{
public void getData(Map<String,Object> arg);
}
In our mybatis xml file,we have element defined for a callable statement. arg is a map which holds IN and OUT parameters.
Our service component is like
#Service("myService")
class MyService{
#Autowired
private MyBatisMapper myMapper;
public void processData(){
Map<String,Object> input = new HashMap<String,Object>();
............
............
myMapper.getDat(input);
Object response = input.get("RESPONSE");
//process response and so on
}
My objective is to write Junits for the service component and don't have to interact with DB. So, I tried to use JMockIt to mock some of the DAO operations
My attempt is ike
#Mocked
#Injectable
private MyBatisMapper myMapper;
#Test
public void testService() {
new NonStrictExpectations(){
{
Map<String,Object> input = new HashMap<String,Object>();
input.put("xxx,"yyy");
myMapper.getData(input);
}
};
}
But when I ran my tests, I noticed that call went through actualy DB , instead of mocked one.
How to make sure only the mocked components gets called, instead of the actual object
#Injectable mock instances only get injected into #Tested objects. And to specify a return value from a mocked method, you need to assign it to the result field. So, the test should look like the following:
#Tested MyService myService;
#Injectable MyBatisMapper myMapper;
#Test
public void testService() {
final Map<String,Object> data = new HashMap<String, Object>();
data.put("RESPONSE", "yyy");
new Expectations() {{
myMapper.getData((Map<String, Object>) any); result = data;
}};
myService.processData();
// Assert some expected outcome.
}
Thank you Rogerio. I tried to follow the approach you mentioned, but still I see the call going to the actual object. There is a point which I did not mention earlier. My project is spring based and the components are all autowired.
My test has
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:spring/test-applicationContext.xml"})
and test-applicationContext.xml has component scan. So I think, Spring is injecting the actual object ignoring the mock instruction.
Am I wrong ?

Protobuf-net serializer for NEventStore 3+

Can anyone point me to a protobuf-net serializer for NEventStore 3.0?
I'm having trouble I think mainly due to the serialization in event store 3 wrapping the event body and headers in an EventMessage.
I'm not sure how to setup the custom serializer correctly.
This is entirely untested guesswork based on a very brief glance at github, but it looks like you want to use the wire-up API to specify a custom serializer, for example:
var store = Wireup.Init()
.UsingSqlPersistence("Name Of EventStore ConnectionString In Config File")
.InitializeStorageEngine()
.UsingCustomSerialization(mySerializer)
... etc
where mySerializer is an instance of a type that implements the ISerialize interface. It looks like this should work:
class ProtobufSerializer : EventStore.Serialization.ISerialize
{
public void Serialize<T>(Stream output, T graph)
{
ProtoBuf.Serializer.Serialize<T>(output, graph);
}
public T Deserialize<T>(Stream input)
{
return ProtoBuf.Serializer.Deserialize<T>(input);
}
}
(so obviously mySerializer here would be a new ProtobufSerializer())

EntityFramework.dll DbContext conflicting with Microsoft.data.Entity.CTP DbContext

Grabbed this from a sample:
protected override ObjectContext CreateDataSource()
{
NorthwindContext nw = new NorthwindContext();
// Configure DbContext before we provide it to the
// data services runtime.
nw.Configuration.ValidateOnSaveEnabled = false;
// Get the underlying ObjectContext for the DbContext.
var context = ((IObjectContextAdapter)nw).ObjectContext;
// Return the underlying context.
return context;
}
Modified it to use the DbContext class that I have in my project.
EDIT: Clarifying that I am casting from a DbContext class just as the sample does:
public class NorthwindContext : DbContext
{
// Use the constructor to target a specific named connection string
public NorthwindContext()
: base("name=NorthwindEntities")
{
// Disable proxy creation as this messes up the data service.
this.Configuration.ProxyCreationEnabled = false;
// Create Northwind if it doesn't already exist.
this.Database.CreateIfNotExists();
}
Running the code gives me an error on the line casting the DbContext:
Unable to cast object of type 'MyProject.MyDbContext' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.
Despite the fact that DbContext implements IObjectContextAdapter:
public class DbContext : IDisposable, IObjectContextAdapter
I've found several questions here on SO and other googled sources, but no solutions I have found work.
I'm using Entity Framework 4.2, attempted to update to the 4.3 beta and I'm not sure if that stuck.
Overall goal is to serve data in WCF as a DataService.
Update: Digging deeper I find that there is an ambiguity issue between what my DbContext was (From EntityFramework.dll ) and the type in the WCF project (from Microsoft.data.Entity.CTP)
Not sure how to get what I want from both here....
Just a reminder, the issue here was that an ambiguity between EntityFramework.dll and Microsoft.Data.Entity.CTP was causing the DataInitializer I had for my DbContext to lose functionality.
I solved this issue by replacing my Initializer here:
public class MyDataInitializer : RecreateDatabaseIfModelChanges<MyData>
{
public void Seed(MyData context)
To:
public class MyDataInitializer : IDatabaseInitializer<MyData>
{
public void InitializeDatabase(MyData context)
And I can now access my DataService.
Just one

How to change configs in Spring.Net

An advantage of an IoC container is that you can swap in a mock service at the bottom of your object graph. However this seems much harder to do in Spring.Net than in other IoC Containers. Here's some code that does it in Unity and has Spring.Net code;
namespace IocSpringDemo
{
using Microsoft.Practices.Unity;
using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
public interface ISomeService
{
string DoSomething();
}
public class ServiceImplementationA : ISomeService
{
public string DoSomething()
{
return "Hello A";
}
}
public class ServiceImplementationB : ISomeService
{
public string DoSomething()
{
return "Hello B";
}
}
public class RootObject
{
public ISomeService SomeService { get; private set; }
public RootObject(ISomeService service)
{
SomeService = service;
}
}
[TestFixture]
public class UnityAndSpringDemo
{
[Test]
public void UnityResolveA()
{
UnityContainer container = new UnityContainer();
container.RegisterType<ISomeService, ServiceImplementationA>();
RootObject rootObject = container.Resolve<RootObject>();
Assert.AreEqual("Hello A", rootObject.SomeService.DoSomething());
}
[Test]
public void UnityResolveB()
{
UnityContainer container = new UnityContainer();
container.RegisterType<ISomeService, ServiceImplementationB>();
RootObject rootObject = container.Resolve<RootObject>();
Assert.AreEqual("Hello B", rootObject.SomeService.DoSomething());
}
[Test]
public void SpringResolveA()
{
IApplicationContext container = ContextRegistry.GetContext();
RootObject rootObject = (RootObject)container.GetObject("RootObject");
Assert.AreEqual("Hello A", rootObject.SomeService.DoSomething());
}
[Test]
public void SpringResolveB()
{
// does not work - what to do to make this pass?
IApplicationContext container = ContextRegistry.GetContext();
RootObject rootObject = (RootObject)container.GetObject("RootObject");
Assert.AreEqual("Hello B", rootObject.SomeService.DoSomething());
}
}
}
For the benefit of Spring, the following needed to be in the App.config file. Clearly this only serves the first spring test, and not the second. Can you put multiple spring configurations in the config file? If so, what is the syntax and how do you access them? Or is there another way to do this?
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<object name="RootObject" type="IocSpringDemo.RootObject, IocDemo" autowire="constructor" />
<object name="service" type="IocSpringDemo.ServiceImplementationA, IocDemo" autowire="constructor" />
</objects>
</spring>
Update
Here is a partial answer based at code at the links that Marko Lahma gave to Mark Pollack's blog. I have the above tests passing, with the following code:
public static class SpringHelper
{
public static T Resolve<T>(this IApplicationContext context, string name)
{
return (T)context.GetObject(name);
}
public static void RegisterType<T>(this GenericApplicationContext context, string name)
{
context.RegisterType(name, typeof(T));
}
public static void RegisterType(this GenericApplicationContext context, string name, Type type)
{
IObjectDefinitionFactory objectDefinitionFactory = new DefaultObjectDefinitionFactory();
ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(objectDefinitionFactory, type);
builder.SetAutowireMode(AutoWiringMode.AutoDetect);
context.RegisterObjectDefinition(name, builder.ObjectDefinition);
}
}
...
[Test]
public void SpringResolveA()
{
GenericApplicationContext container = new GenericApplicationContext();
container.RegisterType<RootObject>("RootObject");
container.RegisterType<ServiceImplementationA>("service");
RootObject rootObject = container.Resolve<RootObject>("RootObject");
Assert.AreEqual("Hello A", rootObject.SomeService.DoSomething());
}
[Test]
public void SpringResolveB()
{
GenericApplicationContext container = new GenericApplicationContext();
container.RegisterType<RootObject>("RootObject");
container.RegisterType<ServiceImplementationB>("service");
RootObject rootObject = container.Resolve<RootObject>("RootObject");
Assert.AreEqual("Hello B", rootObject.SomeService.DoSomething());
}
This raises a few questions to me:
I want to integrate this technique into existing code that uses the usual container. Why do I have to use a different container type, GenericApplicationContext in this case? What if I want to read data into this object from the existing spring config in app.config or web.config? Would it work as the usual context? Could I then write data over these registrations with code?
How can I specify that ISomeService is to be created as a singleton? I don't mean supply a singleton instance to the container, but the container to create the instance, resolving its constructor, and use it when that type is needed.
how can I do the equivalent of container.RegisterType<ISomeService, ServiceImplementationA>(); ? I want to register type mappings to use in all cases where that type is needed by a constructor.
What exactly does container.RegisterType<ServiceImplementationA>("service"); do? It seems to register ServiceImplementationA as the implementation of ISomeService but ISomeServiceis never mentioned, so there could be ambiguity. e.g. what if ServiceImplementationA implemented more than one interface.
What is the string name given to the registration for? It won't work with en empty string, but it doesn't seem to matter what it is.
Am I trying to use spring in a way that it just does not work? I'm trying to use it like other IoC containers, but it's not quite working.
Adding as new answer trying to address the open points...
I want to integrate this technique
into existing code that uses the usual
container. Why do I have to use a
different container type,
GenericApplicationContext in this
case? What if I want to read data into
this object from the existing spring
config in app.config or web.config?
Would it work as the usual context?
Could I then write data over these
registrations with code?
Spring has concrete application context implementations for different kind of initialization tactics. The most common ones to use are GenericApplicationContext (manual), XmlApplicationContext (XML files) and WebApplicationContext (very much like XmlApplicationContext but tailored for web use). They all implement common interface: IApplicationContext which is the preferred way to access these containers.
Unfortonately altering registrations with code usually means that you need to use the specific sub-class directly. With GenericApplicationContext and StaticApplicationContext this is quite natural but XmlApplicationContext is usually considered to be XML only and this ways "fixed" to XML definition.
How can I specify that ISomeService is
to be created as a singleton? I don't
mean supply a singleton instance to
the container, but the container to
create the instance, resolving its
constructor, and use it when that type
is needed.
Your SpringHelper does just that, by default all objects in Spring are singletons. You could alter this behavior by calling ObjectDefinitionBuilder's SetSingleton method with false.
how can I do the equivalent of
container.RegisterType(); ? I want to
register type mappings to use in all
cases where that type is needed by a
constructor.
Spring uses object names (ids) to distinct between different implementations. So if you want to get specific type to serve a specific instance in case that there are many alternatives you should refer to this specific instance by name. If you are using autowiring and your object has dependency to interface ISomeService and there's only one object registered that implements it, the autowiring can set it without ambiguity.
What exactly does
container.RegisterType("service");
do? It seems to register
ServiceImplementationA as the
implementation of ISomeService but
ISomeServiceis never mentioned, so
there could be ambiguity. e.g. what if
ServiceImplementationA implemented
more than one interface.
Continuing from previous answer, this registers singleton of type ServiceImplementationA with name "service". This object comes autowiring candidate with all it's implemented interfaces (and with it's concrete type of course).
What is the string name given to the
registration for? It won't work with
en empty string, but it doesn't seem
to matter what it is.
It matters a great deal as explained earlier. The name is unique id within that context (parent context could have object with same name) and can be used to access specific object registrations. In short where other frameworks may associate a type as key to object registration, Spring uses name.
That's a bit apples and oranges comparison as the unit test uses code configuration for Unity and XML (app.config) configuration for Spring.NET.
If you go the XML route, then you can either comment out old implementation A and define the B implementation as the one to use - that what's configuration is all about right? Other option is to have dedicated XML files for each scenario (configuration setup) and include them via context's resource definitions (you have inline resource now). Other options include file system and assembly, see the web configuration section in Spring.NET's manual for a nice example.
If you go the code configuration route I would suggest to check Spring.NET Recoil and upcoming CodeConfig.