Servlet 3.0 annotations in conjuction with Guice - annotations

I am attempting to update a legacy Guice application, and I was wondering if there is any sort of preferred way of doing things when taking Servlet 3.0 annotations into consideration. For example, my application has a filter, FooFilter, which is defined in the Guice Module Factory method configureServlets(), as follows:
Map<String, String> fooParams = new HashMap<String, String>();
fooParams.put("someParam", "parameter information");
filter("/foo.jsp","/foo/*").through(com.example.filter.FooFilter.class, fooParams);
Is the above binding still necessary, or will it interfere with the following using the #WebFilter Servlet 3.0 annotation:
#Singleton
#WebFilter(
filterName="FooFilter",
urlPatterns={"/foo.jsp", "/foo/*"},
initParams = {
#WebInitParam(name="foo", value="Hello "),
#WebInitParam(name="bar", value=" World!")
})
public class FooFilter implements Filter {
etc....
Which method is now preferred? Will they mess with each other?

I just made quick draft how could a Servlet 3.0 support looks like. There could be a more elegant way to just call filter(Filter Class with WebFilter annotation) in configureServlet method, but that requires updated right to guice-servlet module, which is quite hard to distribute.
Well, what I did is a project at Github: https://github.com/xbaran/guice-servlet3
all you need to do is download and build. It is created on top of Guice 3.0 and works like this:
new Servlet3Module() {
#Override
protected void configureServlets3() {
scanFilters(FooFilter.class.getPackage());
}
};
The Servlet3Module extends ServletModule and contains a scanFilters method with package argument. This method will scan provided package from your classpath and try to register all classes with annotation WebFilter via filter() method.
This scan idea is based on Sitebricks (guice web framework created by Dhanji R. Prasanna) configuration system.
Honestly, I just make a draft, never try if it works. But hopefully it will. If you have any problem or question, just let me know.
PS: The support for servlets, listeners and so on could be added to, if you wish.

Related

Implementing Hypermedia in RESTful JAX-RS Apache CXF

I am working in a RESTful application developed in Apache CXF and I would like to introduce hypermedia functionality to it.
Most of our jaxrs:serviceBeans follow this template:
#GET
#Path("/{exampleId}")
public ExampleJSON get(#PathParam("exampleId") Integer exampleId) {
ExampleJSON example;
// Load data from repository here...
// Add link to self.
String href = javax.ws.rs.core.Link.fromResource(ExampleService.class).build().getUri().toString();
// HypermediaLink is a custom object to hold a "href" and "rel" strings
HypermediaLink linkToSelf = new HypermediaLink();
linkToSelf.setHref(href + example.getId());
linkToSelf.setRel("self");
// Inherited method, just adds a HypermediaLink to a collection in the parent class
example.addHypermediaLink(linkToSelf);
// Return JSON compatible object, JACKSON will serialize it nicely.
return example;
}
This is the basic concept. Keep in mind that I simplified this code for explanation purposes; so, it can be easily understood.
This code works fine; but I am wondering if there is a better way to do this with Apache CXF. I have some ideas for how to enhancing it; however, it will require some custom annotations.
I see some examples using Jersey, but I would like to stick with Apache CXF.
Any help would be appreciated.
Thanks
I would leverage some features of JAX-RS and / or Jackson to implement the link adding under the hood at the serialization level. So you wouldn't need to have a specific field for the link within the bean itself.
You could implement a custom MessageBodyWriter to generate a different JSON payload (for example) for your POJOs than the default. So you could dynamically add the link.
See this answer for more details: How to write an XML MessageBodyWriter provider with jersey.
If you use Jackson for the serialization, you could implement a custom serializer. Note that this is generic and will work for all supported format of Jackson.
Below is a sample code:
public class LinkBeanSerializer extends JsonSerializer<SomeBean> {
#Override
public void serialize(SomeBean bean, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
// Fields
jgen.writeNumberField("id", bean.getId());
// Things could be generic using reflection
// Link
String href = javax.ws.rs.core.Link.fromResource(SomeBean.class).build().getUri().toString();
HypermediaLink linkToSelf = new HypermediaLink();
linkToSelf.setHref(href + bean.getId());
linkToSelf.setRel("self");
jgen.writeObjectField("hypermediaLink", linkToSelf);
jgen.writeEndObject();
}
}
Note that we could make this serializer more generic I think (something like extends JsonSerializer<Object>)
See this answer for more details: Processing JSON response using JAX-RS (how to register the custom serializer within JAX-RS, ...).
Perhaps implementing a WriterInterceptor could solve your problem but there is impact on the beans since you need to have field hypermediaLink. The interceptor could be responsible of filling the field.
See this answer for more details: Jersey Update Entity Property MessageBodyWriter.
IMO the more convenient solution is the second one. It's transparent and support all the formats supported by Jackson.
Hope it helps you,
Thierry

Using Guice/Peaberry for osgi declarative services

I want to solve the following problem and need advice, what the best solution is.
I have a bundle A in which a service interface X is defined. A bundle B provides a service implementation of X and contributes the implementation to the tool. A and B use Google Guice and Peaberry to configure the setup of the objects.
There are two possibilities I can use to contribute the service implementation:
Using an eclipse extension:
In this solution I can use the GuiceExtensionFactory mechanism of Peaberry to create the service implementation using Guice and therefore can inject stuff needed by the implementation. The disadvantage here is that in the bundle defining the extension point, I need the boilerplate code for the resolution of the extensions because there is to my knowledge no way to get the extensions injected into the class which uses the extensions.
This looks like this:
<extension point="A.service.X">
<xservice
...
class="org.ops4j.peaberry.eclipse.GuiceExtensionFactory:B.XImpl"
.../>
</extension>
<extension
point="org.ops4j.peaberry.eclipse.modules">
<module
class="B.XModule">
</module>
</extension>
but I need the boilerplate code like this:
private List<X> getRegisteredX() {
final List<X> ximpls = new ArrayList<>();
for (final IConfigurationElement e : Platform.getExtensionRegistry().getConfigurationElementsFor( X_EXTENSION_POINT_ID)) {
try {
final Object object = e.createExecutableExtension("class"); //$NON-NLS-1$
if (object instanceof X) {
ximpls.add((X) object);
}
} catch (final CoreException ex) {
// Log
}
}
return ximpls;
}
Using an OSGI service:
My main problem here is to ensure that the service is registered. I want the bundle loaded lazily, so at least an access to one of the classes of the bundle is required. Registering the service programmatically using Peaberry has an issue, because nobody ever asks for a class of the bundle. The solution is to provide the service as a declarative service, but I do not know a way to create the service implementation in a way, that I can use Guice to inject required objects.
So I have some questions:
Is there something I do not know so far that implements the code needed to read the extensions at an extension point generically and allows to inject the extensions to the class using the extensions?
Is there a way to ensure that the service is provided even if it is added using the standard Peaberry mechanism, i.e., the bundle is activated when the service is requested?
Is there a way like the GuiceExtensionFactory for declarative services, so that the creation of the service implementation can be done by the injector of the bundle?
Something that look like:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="Ximpl">
<implementation class="some.generic.guiceaware.ServiceFactory:B.Ximpl"/>
<service>
<provide interface="A.X"/>
</service>
</scr:component>
Summarized, I want a service implementation generated by Guice and I want to get the service implementations simply injected into the classes using the service without extensive boilerplate code. Has anybody a solution for that?
Sorry, to ask, but I searched the web for quite a while and so far I did not find a solution.
Thanks and best regards,
Lars
I found a solution, but since I did not find it without a lot of trying out and thinking I thought I share it here. From the options I mentioned in my posting, my solution uses the first one, that is Eclipse extension points and extensions. In order to use Guice in the context of extension points there are two aspects to consider:
Providing an extension that is created by an Guice injector
This is explained very well here: https://code.google.com/p/peaberry/wiki/GuiceExtensionFactory. There is one remark to make from my side. The creation of the extension object is done in an injector inside of the GuiceExtensionFactory, so it is an own context, which needs to be configured by the module given as additional extension to the factory. This can become an issue, if you have other needs that require creating the injector in the bundle on your own.
Defining an extension point so that the extensions are simply injected into the classes which use the extensions.
First thing to do is to define the extension point schema file as normally. It should contain the reference of an interface that has to be implemented by the extensions.
The id of the extension point has to be connected to the interface which is provided by the extensions and which is injected by guice/peaberry. Therefore peaberry provides an annotation to be used to annotate the interface:
import org.ops4j.peaberry.eclipse.ExtensionBean;
#ExtensionBean("injected.extension.point.id")
public interface InjectedInterface {
...
}
On some web pages you also find the information that if the id is equal to the qualified name of the interface, it can be found directly without the annotation but I did not try this out.
In order to enable the injection, you have to do two things to configure the Guice injector creation.
First the EclipseRegistry object of Peaberry has to be set as ServiceRegistry. Second the binding of the extension implementations to a provided service has to be done.
The injector creation has to be done in this way:
import org.osgi.framework.BundleContext;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.ops4j.peaberry.eclipse.EclipseRegistry;
import static org.ops4j.peaberry.Peaberry.*;
void initializer() {
Injector injector = Guice.createInjector(osgiModule(context, EclipseRegistry.eclipseRegistry()), new Module() {
binder.bind(iterable(InjectedInterface.class)).toProvider(service(InjectedInterface.class).multiple());
});
}
The extension implementations can then simply be injected like this:
private Iterable<InjectedInterface> registeredExtensions;
#Inject
void setSolvers(final Iterable<InjectedInterface> extensions) {
registeredExtensions = extensions;
}
With the described way it is possible to have injected extensions which are implemented by classes using Guice to get dependencies injected.
I did not find a solution to use osgi services so far, but perhaps there is someone who has an idea.
Best regards,
Lars

Using an interceptor with Tapestry Resteasy

I have a resource class and I'd like to be able to check an authentication token before the resource method is called, thus avoiding having to pass the token directly into the Resource method.
I have added the following to web.xml:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>com.michael.services.interceptors.AuthorisationInterceptorImpl</param-value>
</context-param>
My interceptor is implemented as follows:
#Provider
public class AuthorisationInterceptorImpl implements javax.ws.rs.container.ContainerRequestFilter {
#Inject
private ApiAuthenticationService apiAuthenticationService
#Override
public void filter(ContainerRequestContext requestContext) {
//Code to verify token
}
}
The filter method is being called before the methods in my resource class; however, the apiAuthenticationService is not being injected and is null when I attempt to call its methods.
I'm using Tapestry 5.3.7, Tapestry-Resteasy 0.3.2 and Resteasy 2.3.4.Final.
Can this be done ?
I don't think this will work, based on a quick glance at the tapestry-resteasy code.
The #Inject annotation is part of tapestry-ioc; if a class is not instantiated by Tapestry, the #Inject annotation is not honored.
Filters defined in web.xml are instantiated by the servlet container (Jetty, Tomcat, etc.) which do not have any special knowledge of Tapestry and Tapestry annotations.
I think you will be better off contributing a filter into Tapestry's HttpServletRequestHandler or RequestHandler pipelines (see their JavaDoc). I'm not sure how you can gain access to the ContainerRequestContext, however.
With tapestry-resteasy you don't need to define the provider in the web.xml file.
If you want to use Tapestry's autobuild mechanism just move your provider to the .rest package together with your resources.
If don't want to use autodiscovery/autobuild just contribute it to javax.ws.rs.core.Application
#Contribute(javax.ws.rs.core.Application.class)
public static void configureRestProviders(Configuration<Object> singletons, AuthorisationInterceptor authorisationInterceptor)
{
singletons.add(authorisationInterceptor);
}
Even though you can use rest providers for security is probably a good idea to take Howard's advice and implement your own filter in the tapestry pipeline.
BTW, you can also give tapestry-security a try :)

JUnit test with GIN injection, without GWTTestCase and overloading gin modules?

I designed a new project using Guice/Gin so I could make our code more modular and swap-able especially when testing.
However, I am not able to find out how to make this work in practice. I was under the impression that I could just create a new Gin/Guice module in my test and install my 'base' module, overloading any bindings that I want to replace with specific testing implementations.
I don't want to have to use GWTTestCase and load my entire module, because it is very slow and unecissary for the types of granular testing I need to do.
I have tried using Jukito (http://code.google.com/p/jukito/), gwt-test-utils (http://code.google.com/p/gwt-test-utils/wiki/HowToUseWithGIN) and also some resources on doing this with guice (http://fabiostrozzi.eu/2011/03/27/junit-tests-easy-guice/).
None of these methods are yielding any results.
I think the Guice approach might work, if I defined a mirror guice module for my Gin module. However I really don't want to have to manage both of these. I really just want to test my GIN module like I would assume people test with Guice.
I feel like this should be really simple, can anyone point me to examples that work?
Update
Another way of looking at this question is:
How do I get the examples on the Jukito site (http://code.google.com/p/jukito/) work when the classes I am injecting are in an exernal Gin module?
**Update - In reference to Thomas Boyer's answer **
Thanks for the hint Tom, I was not able to find examples of using the adapter but I tried augmenting the Jukito examples to use the GinModuleAdapter anyway:
#RunWith(JukitoRunner.class)
public class MyGinTest {
public static class Module extends JukitoModule {
protected void configureTest() {
install(new GinModuleAdapter(new ClientModule()));
}
}
#Test
#Inject
public void testAdd(SyncedDOMModel mod){
assertNotNull(mod);
}
}
When I tried to run this test I recieved this exception:
java.lang.AssertionError: should never be actually called
at com.google.gwt.inject.rebind.adapter.GwtDotCreateProvider.get(GwtDotCreateProvider.java:43)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1031)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.Scopes$1$1.get(Scopes.java:65)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:204)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:198)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:198)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:179)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:109)
at com.google.inject.Guice.createInjector(Guice.java:95)
at com.google.inject.Guice.createInjector(Guice.java:72)
at com.google.inject.Guice.createInjector(Guice.java:62)
at org.jukito.JukitoRunner.ensureInjector(JukitoRunner.java:118)
at org.jukito.JukitoRunner.computeTestMethods(JukitoRunner.java:177)
at org.jukito.JukitoRunner.validateInstanceMethods(JukitoRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:102)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.jukito.JukitoRunner.<init>(JukitoRunner.java:72)
My gin module is part of a GWTP project, and looks like this:
public class ClientModule extends AbstractPresenterModule {
#Override
protected void configure() {
install(new DefaultModule(ClientPlaceManager.class));
bindPresenter(MainPagePresenter.class, MainPagePresenter.MyView.class,
MainPageView.class, MainPagePresenter.MyProxy.class);
bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.main);
bindPresenterWidget(MapTreePresenter.class,
MapTreePresenter.MyView.class, MapTreeView.class);
bindPresenterWidget(MapTreeItemPresenter.class,
MapTreeItemPresenter.MyView.class, MapTreeItemView.class);
bind(ResourcePool.class).to(DefferredResourcePool.class);
bind(WebSocket.class).to(WebSocketImpl.class);
}
}
As you can somewhat see, the class I am injecting in my test SyncedDOMModel, uses a WebSocket which I bind in my module. When I am testing, I don't want to use a real websocket and server. So I want to overload that binding in my test, with a class that basically emulates the whole thing. It's easier to just inject a different implementation of the WebSocket in this case rather than use mocking.
If it helps, this is a basic outline of the SyncedDOMMOdel class:
public class SyncedDOMMOdel {
....
#Inject
public SyncedDOMModel(WebSocket socket){
this.socket = socket;
}
....
}
You can use the GinModuleAdapter to use any GinModule as a Guice Module.
Obviously, you won't benefit from GIN's specific features: default to GWT.create() when something has no particular binding (this includes interfaces and abstract classes, which would throw in Guice), and automatically search for a RemoteService interface when an interface whose name ends Async has no specific binding.
And you won't be able to use anything that depends on JSNI or deferred binding (GWT.create()), as in any non-GWTTestCase unit test.

Serialize aspectj method in GWT

I've try to expose to the client(gwt) an aspectJ method through gwt-rpc, but the gwt client can't find the method defined in an aspect. The class that i expose implements IsSerializable and only it's method are visible to the client interface...the method added by their aspect contrariwise no. How i can fix this? thanks in advice.
p.s. i post a little example for more clarity:
this is the class...
public class Example implements IsSerializable{
private String name;
public setName(String name){
this.name=name
}
}
and this is the aspect...
privileged aspect Example_x{
public int Example.getVersion() {
return this.version;
}
}
The Example.getVersion() method is unavailable on the client side.
TNX
This won't work, as GWT needs access to the source of any Java class that is exposed to the client side. This is necessary to compile them from Java to Javascript. If you modify your classes using AspectJ, the added methods will not be visible to the GWT compiler and therefore not to the client.
I'd say AspectJ is simply the wrong tool for this task. If you want to add some methods to existing classes you could write a (possibly generic) container class that contains an instance of Example as well as the version information from Example_x.