NPE when retrieving application handler - jersey

Using Dropwizard 1.3.17, we retrieve the ServiceLocator as such:
ServiceLocator serviceLocator = ((ServletContainer) environment.getJerseyServletContainer()).getApplicationHandler().getServiceLocator();
When we migrated to Dropwizard 2, this became:
ServletContainer servletContainer = (ServletContainer) Objects.requireNonNull(environment.getJerseyServletContainer());
ApplicationHandler applicationHandler = servletContainer.getApplicationHandler();
InjectionManager injectionManager = applicationHandler.getInjectionManager();
ServiceLocator serviceLocator;
if (injectionManager instanceof ImmediateHk2InjectionManager)
{
serviceLocator = ((ImmediateHk2InjectionManager) injectionManager).getServiceLocator();
}
else if (injectionManager instanceof DelayedHk2InjectionManager)
{
serviceLocator = ((DelayedHk2InjectionManager) injectionManager).getServiceLocator();
}
else
{
throw new IllegalStateException("Expecting an HK2 injection manager");
}
However, ApplicationHandler is null. Any ideas?

We refactored our code not to rely on the service locator prior to org.eclipse.jetty.server.Server.start. Seems to be working.

Related

How to Method#getAnnotatedParameterTypes() in spring proxied class

I'm using spring-boot 2+ and created some custom annotation;
#Target({ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
public #interface MyCustomAnnotation{
}
When doing:
final AnnotatedType[] annotatedTypes = mostSpecificMethod.getAnnotatedParameterTypes();
//this will get the original class
//final Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);
Class<?> annotatedMappedClass = null;
for (AnnotatedType annotatedType : annotatedTypes) {
if (annotatedType.isAnnotationPresent(MyCustomAnnotation.class)) {
annotatedMappedClass = TypeFactory.rawClass(annotatedType.getType());
}
}
it works when bean is not a proxy but when I add the #Transactional annotation it becomes a proxy and stops working. What is the Spring Util to find in the target class?
As far as I understood you'll need the bean. Using:
Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass());
seems to work.
Also a more complex one:
Method method = mostSpecificMethod;
if (AopUtils.isAopProxy(bean)) {
try {
Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);
method = clazz.getMethod(mostSpecificMethod.getName(), mostSpecificMethod.getParameterTypes());
}
catch (SecurityException ex) {
ReflectionUtils.handleReflectionException(ex);
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException("...", ex);
}
}

Getting Class annotation for a given Spring Bean

I have two custom annotation as described below.
CustomAnnotationMain is a Spring Component based annotation.
CustomAnnotationChild is a Spring Bean based annotation.
Below is the code snippet which uses the 2 custom annotations.
#CustomAnnotationMain(value = "parent")
public class MainClass{
#CustomAnnotationChild(value = "child1")
public ObjectBuilder getObject1() {
// logic
}
#CustomAnnotationChild(value = "child2")
public ObjectBuilder getObject2() {
// logic
}
}
Question: How can I get the list of all CustomAnnotationMain annotated classes and also all the beans + annotation infos that are available as part of the component?
I did the following to get all the beans annotated with #CustomAnnotationChild. But I am not sure how to access the class in which the bean is available. I need to access #CustomAnnotationMain for a given bean.
allBuilders = context.getBeansOfType(ObjectBuilder.class);
PS: This is not Spring Boot based project. I use only the spring core libs.
I did something similar. Introduced an interface Proxyable and need to find all the beans annotated with the interface or create proxy s for all defined interfaces.
https://github.com/StanislavLapitsky/SpringSOAProxy/blob/master/core/src/main/java/org/proxysoa/spring/service/ProxyableScanRegistrar.java
In your case you should replace Proxyable with your CustomAnnotationMain.
The logic of ClassPathScanningCandidateComponentProvider definition can be changed to reflect your filter (I need there interfaces only).
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
LOG.debug("Registering #Proxyable beans");
// Get the ProxyableScan annotation attributes
Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ProxyableScan.class.getCanonicalName());
if (annotationAttributes != null) {
String[] basePackages = (String[]) annotationAttributes.get("value");
if (basePackages.length == 0) {
// If value attribute is not set, fallback to the package of the annotated class
basePackages = new String[]{((StandardAnnotationMetadata) metadata).getIntrospectedClass().getPackage().getName()};
}
// using these packages, scan for interface annotated with Proxyable
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment) {
// Override isCandidateComponent to only scan for interface
#Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return metadata.isIndependent() && metadata.isInterface();
}
};
provider.addIncludeFilter(new AnnotationTypeFilter(Proxyable.class));
ControllerFactory factory = getControllerFactory((DefaultListableBeanFactory) registry);
// Scan all packages
for (String basePackage : basePackages) {
for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
try {
Class c = this.getClass().getClassLoader().loadClass(beanDefinition.getBeanClassName());
if (!hasImplementingClass(c, basePackages)) {
//creating missing beans logic is skipped
}
} catch (ClassNotFoundException e) {
throw new SOAControllerCreationException("cannot create proxy for " + beanDefinition.getBeanClassName());
}
}
}
}
}
Hope it helps

bean validation (JSR 303) for primefaces not working

I'm using:
Primefaces 6.1
JSF: 2.2.10
javax.validation:1.1.0.Final
validator impl: hibernate-validator 5.0.1.Final
GAE: 1.9.52
I follow the example for CSV (Client Side Validation) using backend bean from:
https://www.primefaces.org/showcase/ui/csv/bean.xhtml
The expected result should be:
And what I get right now:
The bean validation is not working.
I have below configure in web.xml
<context-param>
<param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
<param-value>true</param-value>
</context-param>
Few similar posts said need downgrade jsf to 2.2.2, I tried but still not working.
Right now the workaround for CSV is either
using jsf tag validation based on the demo
https://www.primefaces.org/showcase/ui/csv/basic.xhtml
For example:
<p:inputText id="age" value="#{beanValidationView.age}" label="Age">
<f:validateLongRange for="age" minimum="10" maximum="20" />
</p:inputText>
Or create my own validator
for example:
http://www.supermanhamuerto.com/doku.php?id=java:validatorinprimefaces
BTW, I don't think it is related to GAE. Because I tried with a new Dynamic Web Project using Tomcat 9, it give me the same result as shown in below screen capture.
Is that any thing(s) I miss configured or having diff version of jar causing that problem?
I got the same error.
I fixed it by upgrading hibernate-validator from:
5.1.3.Final
to:
5.3.5.Final
I kept Primefaces 6.1.
By placing dependencies (i.e slf4j-jdk14, slf4j-api and jboss-el), Hibernate Validator work on Tomcat 9 but not GAE. After configured the log level to FINER , logger show below entriies:
May 04, 2017 9:10:08 AM com.sun.faces.config.processor.ApplicationConfigProcessor addSystemEventListener
FINE: Subscribing for event javax.faces.event.PostConstructApplicationEvent and source javax.faces.application.Application using listener org.primefaces.extensions.application.PostConstructApplicationEventListener
May 04, 2017 9:10:08 AM com.sun.faces.config.processor.ApplicationConfigProcessor isBeanValidatorAvailable
FINE: java.lang.NoClassDefFoundError: javax.naming.InitialContext is a restricted class. Please see the Google App Engine developer's guide for more details.
java.lang.NoClassDefFoundError: javax.naming.InitialContext is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:50)
at com.sun.faces.config.processor.ApplicationConfigProcessor.isBeanValidatorAvailable(ApplicationConfigProcessor.java:434)
at com.sun.faces.config.processor.ApplicationConfigProcessor.registerDefaultValidatorIds(ApplicationConfigProcessor.java:396)
at com.sun.faces.config.processor.ApplicationConfigProcessor.process(ApplicationConfigProcessor.java:353)
at com.sun.faces.config.processor.AbstractConfigProcessor.invokeNext(AbstractConfigProcessor.java:152)
at com.sun.faces.config.processor.LifecycleConfigProcessor.process(LifecycleConfigProcessor.java:137)
That is a "NoClassDefFoundError", however log in FINE level instead of Warning and return more meaningful message. That bad.
So I make a small change to the isBeanValidatorAvailable() as below to make it work on GAE
static boolean isBeanValidatorAvailable() {
boolean result = false;
final String beansValidationAvailabilityCacheKey =
"javax.faces.BEANS_VALIDATION_AVAILABLE";
Map<String,Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
if (appMap.containsKey(beansValidationAvailabilityCacheKey)) {
result = (Boolean) appMap.get(beansValidationAvailabilityCacheKey);
} else {
try {
// Code for Google App Engine
ValidatorFactory validatorFactory = null;
try{
Object cachedObject=FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(BeanValidator.VALIDATOR_FACTORY_KEY);
if (cachedObject instanceof ValidatorFactory) {
validatorFactory=(ValidatorFactory)cachedObject;
} else {
validatorFactory=Validation.buildDefaultValidatorFactory();
}
}catch(ValidationException e) {
LOGGER.log(Level.WARNING, "Could not build a default Bean Validator factory",e);
}
if (null != validatorFactory) {
appMap.put(BeanValidator.VALIDATOR_FACTORY_KEY, validatorFactory);
result = true;
}
LOGGER.log(Level.FINE, "result=" +result +", validatorFactory=" +validatorFactory);
/* incompatible with Google App Engine
*
Thread.currentThread().getContextClassLoader().loadClass("javax.validation.MessageInterpolator");
// Check if the Implementation is available.
Object cachedObject = appMap.get(BeanValidator.VALIDATOR_FACTORY_KEY);
if(cachedObject instanceof ValidatorFactory) {
result = true;
} else {
Context initialContext = null;
try {
initialContext = new InitialContext();
} catch (NoClassDefFoundError nde) {
// on google app engine InitialContext is forbidden to use and GAE throws NoClassDefFoundError
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, nde.toString(), nde);
}
} catch (NamingException ne) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, ne.toString(), ne);
}
}
try {
Object validatorFactory = initialContext.lookup("java:comp/ValidatorFactory");
if (null != validatorFactory) {
appMap.put(BeanValidator.VALIDATOR_FACTORY_KEY, validatorFactory);
result = true;
}
} catch (NamingException root) {
if (LOGGER.isLoggable(Level.FINE)) {
String msg = "Could not build a default Bean Validator factory: "
+ root.getMessage();
LOGGER.fine(msg);
}
}
if (!result) {
try {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
appMap.put(BeanValidator.VALIDATOR_FACTORY_KEY, factory);
result = true;
} catch(Throwable throwable) {
}
}
}
*/
} catch (Throwable t) { // CNFE or ValidationException or any other
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Unable to load Beans Validation");
}
}
appMap.put(beansValidationAvailabilityCacheKey, result);
}
return result;
}
After all this JSR 303 (Bean Validation) problem is related to GAE restriction on JSF2.
A working copy can get from Google Drive.

Test case using SpringJunitRunner

I want to write junit test case for the below code with springJunitRunner.
the below piece of code is one service in a class.
#Component
#Path(/techStack)
public class TechStackResource {
#Autowired
private transient TechStackService techStackService;
#GET
#Path("/{id}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getTechStackById(final #PathParam("id") Integer technicalstackid) {
final TechStackResponse response = new TechStackResponse();
int statusCode = Constants.HTTP_STATUS_OK_200;
try {
TechStackModel techStackModel = techStackService.findObjectById(technicalstackid);
response.setGetTechStackDetails(GetTechStackDetails.newBuilder().technicalStack(techStackModel).build());
if (techStackModel == null) {
statusCode = Constants.HTTP_STATUS_ERROR_404;
}
} catch (EmptyResultDataAccessException erde) {
} catch (Exception e) {
LOGGER.error("Exception occured in TechStackResource.getTechStackById(technicalstackid) ", e);
throw new APMRestException(
"Exception while executing TechStackResource.getTechStackById(technicalstackid) ",
Constants.UNKNOW_ERROR, e);
}
return Response.status(statusCode).entity(response).build();
}
}
the configuration in web.xml for servlet is
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
Since you are using Jersey as well as Spring, you can use the SpringJunitRunner only to wire-up TechStackResource with its dependency TechStackService.
In order to test your REST handler method getTestStackById, you could go the POJO approach and invoke it directly. Alternatively, you can use Jersey's own MockWeb environment. To find out more about this, I recommend looking at the Jersey example sources, e.g. HelloWorld.

How to use jersey 2.0 guice on grizzly

I want to use Guice + Jersey 2.0 on Grizzly. According to this How to use guice-servlet with Jersey 2.0? discussion there is no direct Guice integration for Jersey2 at present but it can be achieved using HK2 as a bridge. I also checked the sample project in Github https://github.com/piersy/jersey2-guice-example-with-test . This project is implemented using Jetty.
But my problem is to implement it in Grizzly. On Jetty it is used like this
#Inject
public MyApplication(ServiceLocator serviceLocator) {
// Set package to look for resources in
packages("example.jersey");
System.out.println("Registering injectables...");
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(Main.injector);
}
My problem on grizzly is , how to get this serviceLocator object?
Thank you.
I have created the sample here
https://github.com/oleksiys/samples/tree/master/jersey2-guice-example-with-test
The Grizzly initialization code looks like this:
final URI uri = UriBuilder.fromUri("http://127.0.0.1/")
.port(8080).build();
// Create HttpServer
final HttpServer serverLocal = GrizzlyHttpServerFactory.createHttpServer(uri, false);
// Create Web application context
final WebappContext context = new WebappContext("Guice Webapp sample", "");
context.addListener(example.jersey.Main.class);
// Initialize and register Jersey ServletContainer
final ServletRegistration servletRegistration =
context.addServlet("ServletContainer", ServletContainer.class);
servletRegistration.addMapping("/*");
servletRegistration.setInitParameter("javax.ws.rs.Application",
"example.jersey.MyApplication");
// Initialize and register GuiceFilter
final FilterRegistration registration =
context.addFilter("GuiceFilter", GuiceFilter.class);
registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), "/*");
context.deploy(serverLocal);
serverLocal.start();
add dependecy
compile group: "org.glassfish.hk2", name: "guice-bridge", version: "2.4.0"
create feature
public class GuiceFeature implements Feature {
#Override
public boolean configure(FeatureContext context) {
ServiceLocator serviceLocator = ServiceLocatorProvider.getServiceLocator(context);
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
Injector injector = Guice.createInjector(new AbstractModule() {
#Override
protected void configure() {
bind(YYY.class).to(ZZZ.class);
}
});
guiceBridge.bridgeGuiceInjector(injector);
return true;
}
}
register feature
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(GuiceFeature.class);

Resources