Ad-Hoc type conversion in JOOQ DSL query - jooq

scenario:
we store some encrypted data in db as blob. When reading/saving it, we need to decrypt/encrypt it using an external service.
because it is actually a spring bean using an external service, we cannot use the code generator like dealing with enums.
I don't want to use dslContext.select(field1, field2.convertFrom).from(TABLE_NAME) because you need to specify every fields of the table.
It is convenient to use dslContext.selectFrom(TABLE_NAME). wonder if any way we can register the converter bean in such query to perform encrypt and decrypt on the fly.
Thanks
Edit: I ended up using a service to encrypt/decrypt the value when it is actually used. Calling an external service is relatively expensive. Sometimes the value isn't used in the request. It may not make sense to always decrypt the value when reading from db using the converter.

because it is actually a spring bean using an external service, we cannot use the code generator like dealing with enums.
Why not? Just because Spring favours dependency injection, and you currently (as of jOOQ 3.15) cannot inject anything into jOOQ Converter and Binding instances, doesn't mean you can't use other means of looking up such a service. Depending on what you have available, you could use some JNDI lookup, or other means to discover that service when needed, from within your Converter.
Another option would be to use a ConverterProvider and register your logic inside of that. That wouldn't produce your custom type inside of jOOQ records, but whenver you convert your blob to your custom data type, e.g. using reflection.
How to access Spring Beans without Dependency Injection?
If you need to access your Spring Beans you don't need Dependency Injection. Simply create the following class and you can get beans from the static method getBean():
#Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHolder.applicationContext = applicationContext;
}
}

Related

How to create a CDI Interceptor which advises methods from a Feign client?

I've been trying to figure out how to intercept methods defined in a Feign client with CDI (1.2) interceptors. I need to intercept the response value the client is returning, and extract data to log and remove some data prior to it being returned to the calling process.
I'm running a Weld 2.3 container which provides CDI 1.2. In it, I would like to create a CDI interceptor which is triggered everytime a call to filter() is made.
public interface MyRepository {
#RequestLine("POST /v1/data/policy/input_data_filtered")
JsonNode filter(Body body);
}
and a matching Producer method:
#Produces
public MyRepository repositoryProducer() {
return Feign.builder()
.client(new ApacheHttpClient())
.encoder(new JacksonEncoder(mapper))
.decoder(new JacksonDecoder(mapper))
.logger(new Slf4jLogger(MyRepository.class))
.logLevel(feign.Logger.Level.FULL)
.target(MyRepository.class, "http://localhost:9999");
}
I've tried the standard CDI interceptor way by creating an #InterceptorBinding and adding it to the interface definition, but that didn't work. I suspect because the interceptor must be applied to the CDI bean(proxy) and cannot be defined in an interface. I tried applying it to the repositoryProducer() method but that too was non functional.
I've read about the javax.enterprise.inject.spi.InterceptionFactory which is availabel in CDI 2.0, but I don't have access to it.
How can I do this in CDI 1.2? Or alternatively, is there a better interceptor pattern I can use that is built into Feign somehow?
The short, somewhat incorrect answer is: you cannot. InterceptionFactory is indeed how you would do it if you could.
The longer answer is something like this:
Use java.lang.reflect.Proxy to create a proxy implementation of the MyRepository interface.
Create an InvocationHandler that performs the interception around whatever methods you want.
Target Feign at that proxy implementation.

Does ServiceStack's default IoC have something similar to ninject's .ToFactory() Method?

Using ninject, I'm able to create an abstract factory using the following syntax from the application's composition root:
kernel.Bind<IBarFactory>().ToFactory();
Does ServiceStack's default IoC container similar functionality? I'd like to implement an abstract factory in one of my service classes in order to create repositories as needed.
One suggestion I've heard was to use:
HostContext.Container.Resolve<[InsertDependancyHere]>()
but I'd like to avoid creating access to the container outside of the composition root (the Apphost.cs file).
As far as i could tell, ServiceStack's Funq IoC implementation does not include this Abstract Factory implementation, like Ninject's Abstract Factory support (or Castle Windsor's Typed Factory Facility, which i used to use).
You can still avoid Service Locator anti-pattern by creating a concrete Factory implementation and injecting that to your classes.
public class BarFactory : IBarFactory
{
// constructor inject dependencies to the factory - no service locator
public BarFactory() { ... }
// create objects from factory
public IBar GetBar() { ... }
}
Your other classes can inject IBarFactory and call it directly.
Func is bare-bones by design, so will not have all the same features. ServiceStack added some features, but mostly having to do with autowiring registration.
If you can't create a concrete implementation for your factories, this other SO answer may show you how to do it yourself.

How to specify and organize OXM_METADATA_SOURCE in glassfish v4 MOXy Provider?

I am a fan of both Glassfish and MOXy, and it's good news for me that MOXy had been bundled into Glassfish v4.
I had read and tried a few of MOXy examples on the internet, I like the dynamic OXM_META_DATA_SOURCE part, since while providing RESTful services, the "client perspective" is very flexible than domain classes.
So here is the problem:
Different RESTful services can have different views from same domain classes, and in my work it's very common case. So there can be a lot of binding OXM metadata files for every service. And as we know a single OXM metadata file can only correspond to a single java package. So there will be much more OXM metadata files to maintain.
Back to JAX-RS, Is there any framework to design patterns or best practices to finish the mapping between OXM metadata file set and the service itself?
You can try new feature called Entity Filtering which has been introduced in Jersey 2.3. Even though Entity Filtering is not based on OXM_META_DATA_SOURCE you can achieve your goal with it:
Let's assume you have a following domain class (annotations are custom entity-filtering annotations):
public class Project {
private Long id;
private String name;
private String description;
#ProjectDetailedView
private List<Task> tasks;
#ProjectAnotherDetailedView
private List<User> users;
// ...
}
And, of course, some JAX-RS resources, i.e.:
#Path("projects")
#Produces("application/json")
public class ProjectsResource {
#GET
#Path("{id}")
public Project getProject(#PathParam("id") final Long id) {
return ...;
}
// ...
}
Now, we have 2 detailed views defined on domain class (via annotations) and the resource class. If you annotate getProject resource method with:
#ProjectDetailedView - returned entity would contain id, name, description AND a list of tasks from Project
#ProjectAnotherDetailedView - returned entity would contain id, name, description AND a list of users from Project
If you leave the resource method un-annotated the resulting entity would contain only: id, name, description.
You can find more information about Entity Filtering in the User Guide or you can directly try it in our example: entity-filtering.
Note 1: Entity Filtering works only with JSON media type (via MOXy) at the moment. Support for other media types / providers is planned to be added in the future.
Note 2: Jersey 2.3 is not integrated into any (promoted) build of GF 4.0. The next Jersey version that should be part of GF 4.0 is 2.4. We plan to release 2.4 in the next few weeks.

How to make a serviceloader created class handle container managed objects

I'm currently writing a library where I want the user of my library to implement an interface. From within my library I'm calling this implementation.
I'm using ServiceLoader to instantiate the implementation provided by the integrator and it works just fine. The integrator calls a start() method in my library and in the end he gets something in return. The implementation is used to give me some things along the way that I need in order to get to the final result.
(I'm deliberately not using CDI or any other DI container 'cause I want to create a library that can be used anywhere. In a desktop application, a spring application an application using guice...)
Now I'm facing a problem. I'm creating a showcase in which I'm using my own library. It's a webapplication where I'm using jsf and CDI. When I instantiate the implementation provided in said webapp from within my library, I'm dealing with a non-container managed object. But since this implementation needs to use container managed objects I'm kinda screwed since this can never work.
Example:
Interface in lib:
public interface Example{
public abstract String getInfo();
}
Implementation in war:
public class ExampleImpl implements Example{
#Inject
private ManagedBean bean;
public String getInfo(){
return bean.getSomethingThatReturnsString();
}
}
As you can see this is a huge problem in the way my library is build since the bean will always be null... This means no one using a DI container can use my library. I know I can get the managedbean by doing a FacesContext lookup and get the managedbean but more importantly, my library isn't very well designed if you think about it.
So to conclude my question(s):
Is there any way I can make the serviceloader use a DI container to instantiate the class?
Anyone who knows a better way to fix my problem?
Anyone who knows a better way to get the things I need without making the integrator implement an interface but I can get information from the integrator?
I know this is a quite abstract question but I'm kinda stuck on this one.
Thanks in advance
As the implementation of Example is not performed within the CDI container the injection doesn't happen. What you can do is to lookup the bean manually using the BeanManager. According to the docs, the BeanManager is bound to the jndi name java:comp/BeanManager. Using the following code you can get the BeanManager within your implementation class and lookup the dependencies manually:
InitialContext context = new InitialContext();
BeanManager beanManager = (BeanManager) context.lookup("java:comp/BeanManager");
Set<Bean<?>> beans = beanManager.getBeans(YourBean.class, new AnnotationLiteral<Default>() {});
Bean<YourBean> provider = (Bean<YourBean>) beans.iterator().next();
CreationalContext<YourBean> cc = beanManager.createCreationalContext(provider);
YourBean yourBean = (YourBean) beanManager.getReference(provider, YourBean.class, cc);
where YourBean is the dependency you are looking for.

Mapping to an internal type with AutoMapper for Silverlight

How do I configure my application so AutoMapper can map to internal types and/or properties in Silverlight 5? For example, I have the following type:
internal class SomeInfo
{
public String Value { get; set; }
}
I try to call Mapper.DynamicMap with this type as the destination and I receive the following error at runtime:
Attempt by security transparent method
'DynamicClass.SetValue(System.Object, System.Object)' to access
security critical type 'Acme.SomeInfo' failed.
I've tried instantiating the class first, then passing the instance to DynamicMap as well as changing the class scope to public with an internal setter for the property. I've also marked the class with the [SecuritySafeCritical] attribute. All of these tests resulted in the same error message.
The only way I've been able to get past this is to completely expose the class with public scope and public setters. This is, of course, a problem as I am developing a class library that will be used by other developers and using "internal" scope is a deliberate strategy to hide implementations details as well as make sure code is used only as intended (following the no public setters concept from DDD and CQRS).
That said, what can I do to make it so AutoMapper can work with internal types and/or properties?
(Note: The class library is built for SL5 and used in client apps configured to run out-of-browser with elevated trust.)
This is more of a Silverlight limitation - it does not allow reflection on private/protected/internal members from outside assemblies, see:
http://msdn.microsoft.com/en-us/library/stfy7tfc(VS.95).aspx
Simply put - AutoMapper can't access internal members of your assembly.

Resources