CXF DynamicClientFactory efficiency - performance

I need to generate Java client for web service. I have two choices to do that one is use Apache CXF DynamicClientFactory class and the other is use JAX-WS Dispatch API.
From CXF documentation I understood that DynamicClientFactory class will generate the web service SEI, data classes at runtime (using wsdl2Java tool). If I want to call any web service method I need to load the appropriate data class name and I needs to set the parameter using reflection like follows.
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("people.wsdl", classLoader);
Object person = Thread.currentThread().getContextClassLoader().loadClass("com.acme.Person").newInstance();
Method m = person.getClass().getMethod("setName", String.class);
m.invoke(person, "Joe Schmoe");
client.invoke("addPerson", person);
In the above code Person class is generated at runtime by CXF and reflection is used to set the property values.
My question here is: if I want to set 20 parameter values, then I needs to make 20 reflection call to do that. Is this an efficient way to do that? Or is there any alternative? Or is better to use Dispatch API from JAX-WS? Please help me.

Related

Why use spring beans instead of object initialization

I am trying to understand the idea of spring beans and why I should use them. If I create a bean and use it to print something out like this.
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Account acc = (Account)context.getBean("account");
acc.printAccName();
Why not just create an object of that class like this
Account acc2 = new Account();
acc.printAccName();
I have been watching some video's and did some reading but I did not get an answer why it is better.
Usually what you inject is business logic or services which typically is what changes in a system.
You are trying to inject a domain object Account these objects are not subject to change so it is okay to create the object via new. Perhaps, this is what it is confusing you.
The idea, is to let the container handle the instantiation of your logic or services that change regularly so you can swap them easily without having to open the client classes, because these might be already in production, tested and a developer could potentially introduce new bugs and break things. One way to avoid this is to follow a principle called Open-Closed principle. Then you code to abstractions so you can easily inject concrete implementations via dependency injection.
Imagine the following escenario. For a bookstore, you have different implementations of how to save a book into a database e.g. using JDBC BookServiceJDBCImpl, or using an ORM BookServiceHibernateImpl etc..
// Create & get the Spring container, where you configure your implementations
// e.g. bookServiceJDBC, or bookServiceHibernate
ApplicationContext container = new ClassPathXmlApplicationContext("spring-config.xml");
// the container loads the appropriate bean say bookServiceHibernate
BookService bookService = (BookService) container.getBean("bookService");
//Create a new book this is a domain object usually you use new
Book newBook = new Book("1234", "Spring in Action","Rod Johnson");
//Now save the book using the implementation defined in the
//container
bookService.registerNewBook(newBook);
This is how part of the container file may look like, in here you define the concrete implementation:
<bean id="bookService" class="service.BookServiceHibernateImpl"/>
By letting the container handle this you could inject different implementations without having to touch the client class or even knowing which implementation will be passed.
Check this Dependency Injection blog post it explains a way to achieve it using Spring.
Bare in mind that in Spring you can use java annotations or xml, and that there are different ways to inject dependencies e.g. via get/set, constructors etc this is just an illustrative example of the general DI concept. The design is up to the developer.
Another reason why you would use beans is to aid testing.
We also extract the RestTemplate into a #Bean to make it easier to
test (it can be mocked more easily that way). Link

How to map service factory PIDs to their `ObjectClassDefinition`

In OSGi R6 I desire to programmatically validate user-supplied String configuration properties plus a service factory PID against what is supported by whatever configurable #Component (or ManagedServiceFactory) that declares it configures this PID, e.g. #Component(configurationPid=some.service.factory.pid, ...). Additionally, I want to somehow convert valid String properties to their appropriate property types. Looking through the OSGi Compendium, it seems the Metatype Service is what I'm looking for.
If that's correct, given the following:
Applicable components uses component property types to specify their configuration
Component property types are annotated with #ObjectClassDefinition
Components are annotated with #Designate, mapping it to the applicable #ObjectClassDefinition
Is this the most straightfoward way to map factory PIDs to their ObjectClassDefinition:
Call BundleContext.getBundles(). For each bundle, call MetaTypeService.getMetaTypeInformation(Bundle).
For each returned MetaTypeInformation call MetaTypeInformation.getFactoryPids() and filter on the factory PIDs I care about.
For applicable MetaTypeInformation, call MetaTypeInformation.getObjectClassDefinition(String, String) to obtain the ObjectClassDefinition, using either a default or specific locale.
(Tangential, the above seems expensive to perform each time, so caching bundle IDs, mapping them to associated factory PIDs, and keeping the cache up-to-date somehow seems appropriate.)
Or, is there some other OSGi magic that can be programmatically queried with a service factory PID, which returns something that gets to some ObjectClassDefinition quicker than the above process?
Update 1
Stepping back, I'm writing a CRUD-wrapper around ConfigurationAdmin for each of my configurable components. I'm trying to avoid createFoo, deleteFoo, updateFoo, createBar, ... My application happens to be amenable to URIs. So my working approach was to use Metatype Service, pass in a parsed URI query (Map<String, List<String>>), and then utilize Metatype Service to validate and reconstruct these values, circling back to the OP. (On the side, seems like a not-pretty hack to me.)
Another approach was to use aQute.bnd.annotations.metatype.Configurable.createConfigurable(Class, Map), which I preferred more! Until I saw this bnd GitHub comment:
The bnd metatype annotations are deprecated in bnd 3.2 and will be removed in bnd 4.0. These annotations are replaced by the OSGi metatype annotations.
So I didn't want to rely on that package if it's going away soon. I looked at what Felix does and didn't want to use their equivalent Configurable class. I'm all ears on different approaches!
Update 2
Reducing this more, I'd like to validate potentially user-supplied key/values configuration properties to ensure they're applicable for some configuration pid, prior to calling ConfigurationAdmin.createFactoryConfig. Maybe this is overkill?
I once created a class that takes the configuration class, creates a proxy, and then uses this proxy to get the name of the method and the type. It was used something like this:
ConfigHelper<Config> helper = new ConfigHelper( Config.class, "my.pid");
int port = helper.get().port(); // get the configuration
helper.set( helper.get().port(), 1000);
helper.update();
The proxy you get from the get would record the method when one of the methods is called. On the set method it would use the last called proxy method to identify the property. It would then convert the given value to the property type based on the method's return value. The bnd converter is ideal for this but I think Felix now has a standard OSGi converter. (Which is based on the ideas of the bnd converter.)
The method name is then used as the property. The name mangling necessary is defined in an OSGi spec. This allows you to use underscores, Java keywords, and dotted names.
So this would allow you to roundtrip configurations. No worry about the types, they will automatically fall in their place.
Updated This is updated after I understood the question better
Updated 2 Added an example at https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.osgi.configuration.util

Can i access request parameter in jackson BeanSerializerModifier?

I am using Jersey to implement rest api and Jackson to provide JSON support. I am trying to remove certain properties before serialization by overriding BeanSerializerModifier.changeProperties method.
But removing properties will be based on query parameter. Is there any way to access the query parameter in my implementation?
Use of BeanSerializerModifier itself would get complicated as the method is only called once when construction necessarily JsonSerializer for the first time. As to passing query parameters, you could pass them using contextual attributes and ObjectWriter (constructed from ObjectMapper), but that means taking over quite a bit of serialization automation from Jersey.
There is one mechanism that could be helpful in modifying serialization aspects without taking over the whole process: registering ObjectWriterModifier, using ObjectWriterInjector. These are part of Jackson JAX-RS provider, added in Jackson 2.3. Without knowing more details I don't know how easy this would be; part of the issue is that query parameters are more of an input side things, so there is no direct access to them from output processing side.

Parsing a POJO to JSON using JAX-RS and not using any speific implemnation code

I was looking at internals of jersey, on how it converts a simple POJO to Json. Jersey has an interface Providers, which will provide list of contextResolvers given the class and mediaType. once we get the contextResolver, we can get the Context and Marshaller from it, which can used to get the json string, like show below.
lets assume we want to serialize the Pojo "obj". the code will look like follows
Providers ps = ...
ContextResolver<JAXBContext> resolver = ps.getContextResolver(obj.getClass(), MediaType.APPLICATION_JSON_TYPE);
JAXBContext ctx = resolver.getContext(obj.getClass());
ctx.createMarshaller().marshal(obj, writer);
By above way we can convery any POJO which has a valid context resolver to json. but the question is how do we get the handler for Providers.
PS: i have not compiled this code, but from what i can see from source this is what jersey does. On why i am doing all this stuff, so that we can convert a object to JSON directly with JAX-RS apis. instead of using any implementation code.
In a JAX-RS resource clas, use the #Context annotation to tell Jersey to inject the producers:
#Context Producers producers;
So your question is : "how to find providers" ?
You have to write code to find classes in the classpath which are Annotated with #Provider.

Spring boot actuator - Implement custom metrics

I would like to implement custom metric or statistics to my spring boot rest web service using actuator but i am not able to find simple tutorials.
For example:
how to show how many times a certain controller was called and what exact parameter field was filled?
how can i create a metric that when its URL is called, it runs certain query and shows back a json with some result
This seems like a good scenario for AOP (Aspect Oriented Programing) as this will allow you to separate this statistic logic from the business logic.
Have a look at Spring doc for more info about AOP and how to achieve that with Spring.
You can then define a pointcut on your controller and have a service for counting (and probably then storing) the data.
Refer below link
AOP Example
For point two the solution is to create an endpoint class (it can be or not a rest controller class). For example:
#Component
#RestControllerEndpoint(id = "pfm-statistics")
public class StatisticsEndpoint {
#GetMapping(value = "/", produces = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet")
#ResponseBody
public byte[] generateStatisticsAsExcel() {
...
Note that the ID is the path to be called from URL. We can create a simple endpoint too and just return a string if we want. In this case instead of #RestControllerEndpoint annotation we can use #Endpoint, as a side note, the id should always contain dash

Resources