Servlet exception deploying maven enterprise project - maven

I get this error when I try to access to the servlet named BookingServlet
Grave: exception caught
javax.naming.NamingException: Lookup failed for 'java:global/it.volaconnoi_VolaConNoi_webapp-ear_ear_1.0-SNAPSHOT/it.volaconnoi_VolaConNoi_webapp-ejb_ejb_1.0-SNAPSHOT/BookingBean!it.volaconnoi.logic.BookingBeanInterface' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: it.volaconnoi_VolaConNoi_webapp-ear_ear_1.0-SNAPSHOT]
and this is the screenshot
The project is deployed correctly but I don't understand why I get this error. Do you any suggest?
As you may see the booking servlet is in its place
EDIT
BookingBeanInterface bookingBean = lookupBookingBeanLocal();
private BookingBeanInterface lookupBookingBeanLocal() {
try {
Context c = new InitialContext();
return (BookingBeanInterface) c.lookup("java:global/it.volaconnoi_volaconnoi-webapp-ear_ear_1.0-SNAPSHOT/it.volaconnoi_volaconnoi-webapp-ejb_ejb_1.0-SNAPSHOT/BookingBean!it.volaconnoi.logic.BookingBeanInterface");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}

Really not enough description, you should describe where is your class BookingBean is located, and by what means it registered in JNDI. But if we assume that registration is correct, you could try to lookup it using following string:
c.lookup("java:app/BookingBean/it.volaconnoi.logic.BookingBeanInterface");
See more description here: http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html

Related

Spring tries to initialize AutoConfiguration beans using default constructor

We are having issues starting up our Spring Boot Web application. The main problem to properly diagnose the startup is that it only seems to happen in 1% of the startups. In 99% of the startup procedures all works fine and we end up having a properly working spring boot application. However in those 1% of those cases we see issues like this:
WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'errorPageFilterRegistration' defined in org.springframework.boot.web.servlet.support.Error
PageFilterConfiguration: Unsatisfied dependency expressed through method 'errorPageFilterRegistration' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'errorPageFilter' defined in org.springframework.boot.web.servlet.support.ErrorPageFilterConfiguration: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.spring
framework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigu
re.web.servlet.error.ErrorMvcAutoConfiguration]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.<init>() []
For some reason it tries to initialize AutoConfiguration beans by using a default constructor which obviously is not present. There is a constructor present which should be autowired.
Also the AutoConfiguration that is in the stacktrace can be different. Sometimes it is another one like e.g. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
Any help or ideas on why this could be happening is appreciated. As this happens very occasionally this is hard to debug as we cannot relyably reproduce. Note that the stacktrace does not contain any custom code. Our application is quite big and we rely mostly on #Configuration classes to do configure the Beans.
Why would spring attempt to initialize an AutoConfiguration bean with a default constructor ?
The errorPageFilterConfiguration source of spring looks like this:
#Configuration(proxyBeanMethods = false)
class ErrorPageFilterConfiguration {
#Bean
ErrorPageFilter errorPageFilter() {
return new ErrorPageFilter();
}
#Bean
FilterRegistrationBean<ErrorPageFilter> errorPageFilterRegistration(ErrorPageFilter filter) {
FilterRegistrationBean<ErrorPageFilter> registration = new FilterRegistrationBean<>(filter);
registration.setOrder(filter.getOrder());
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
}
According to the stack on creation of the errorPageFilter it is initializing the ErrorMvcAutoConfiguration as a prerequisite ? Why ?
We are not initializing these beans manually. The only relevant code for error page handling that we have is this following:
#Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryCustomizer() {
return webServerFactory -> {
ErrorPage errorPage = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
webServerFactory.addErrorPages(errorPage);
};
}
This is a bug in Spring framework, introduced in version 5.3 in AbstractBeanFactory.
BeanPostProcessorCacheAwareList and accesses to the beanPostProcessors instance are not Thread safe. If multiple Threads are running during initialization and a Thread calls getBeanPostProcessorCache() while another Thread is calling addBeanPostProcessors, you can create a cache which does not contain all BeanPostProcessor instances and thus doesn't find the appropriate constructor.
I will submit a bug for this to spring-framework.
https://github.com/spring-projects/spring-framework/blob/16ea4692bab551800b9ba994ac08099e8acfd6cd/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java#L964
Issue created : https://github.com/spring-projects/spring-framework/issues/29299

How to handle com.netflix.client.ClientException in Spring Cloud

I have two services: A and B. B makes a request via feign client when starts.
But when A is unavailable I get com.netflix.client.ClientException
Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: A
I'm looking for the best practice for handling such an exception
right now there is no official way to catch FeignClient exception. but you can handle FeignClient exception by catching as a java.lang.Exception and throw your own exception.
for ex:
try{
feignClient.feignMethod();
} catch(Exception ex){
//throw your own exception
throw new CustomFeignException();
}

i am getting class cast exception in bean factory in the main file while compiling

Exception in thread "main" java.lang.ClassCastException :
org.springframework.beans.factory.xml.XmlBeanFactory cannot be cast to
org.springframework.beans.factory.BeanFactory at
com.ashish.Test.main(Test.java:11)
How can I do to resolve this exception? Even after casting I am getting the same exception.
You can try the following
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
But, it is recommended to use ApplicationContext as it provides more benefits than just a beanfactory.
context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student=(Student)factory.getBean("studentbean");

Groovy-Spring Integration Issue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
We have developed an application using following technologies stack:
Struts 2.1
Springs 3.1
Groovy 1.8
Tomcat 6.0.26 - For deployment
Our requirement is to migrate a specific layer of application to Groovy. We have migrated that layer to groovy and application is working fine. After the migration groovy beans are initialized properly by spring container but we are not able to utilize the 'dynamic language' feature of Groovy. That is when we modify Groovy script, updated changes are not reflected back to application dynamically.
For reference I am attaching a method of groovy script (GroovyConnection.groovy):
#Component
class GroovyConnection implements EndPointManager, Serializable{
private static final long serialVersionUID = 1481681752777429674L;
private final static Logger log = Logger.getLogger(GroovyConnection.class);
private static final String DESTINATION_DIR = ARTIFACT_DIR_PATH.toString()+"/";
private static final String JIVE_USER = ""; //"jivescpt";
/**
* #param default
*/
public GroovyConnection() {
super();
jschInstance = new JSch();
}
public String executeCommands(Session session, String inputCommand, Device device) {
log.info("Entering executeCommand() device:" + inputCommand);
Channel channel = null;
PipedOutputStream commandIO = null;
InputStream sessionInput = null;
InputStream sessionOutput = null;
InputStream sessionError = null;
String commandResponse = null;
try {
channel = session.openChannel("shell");
commandIO = new PipedOutputStream();
sessionInput = new PipedInputStream(commandIO);
channel.setInputStream(sessionInput);
sessionOutput = channel.getInputStream();
sessionError = channel.getExtInputStream();
channel.connect();
return fireCommandsOnTerminal(session, commandIO, sessionOutput, sessionError, inputCommand, device);
}
catch (JSchException e) {
log.error(AutomationConstants.ERROR_MSG.toString(), e);
}
catch (IOException e) {
log.error(AutomationConstants.ERROR_MSG.toString(), e);
}
catch (InterruptedException e) {
log.error(AutomationConstants.ERROR_MSG.toString(), e);
}
finally {
boolean isClosed = GroovyConnectionHelper.closeAll(session, channel, commandIO, sessionInput, sessionOutput, sessionError);
if (!isClosed) {
return AutomationUtils.getPropertyValue("jive.vpn.error.msg");
}
}
log.info("Exiting executeCommand() device:" + inputCommand);
return commandResponse;
}
}
Groovy-context file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<lang:defaults refresh-check-delay="2000"/>
<lang:groovy id="endPointManager"
script-source="classpath:GroovyConnection.groovy" refresh-check-delay="1000">
</lang:groovy>
</beans>
Even after given refresh-check-delay time for 1 second groovy beans are not behaving accordingly at runtime. I have to restart Tomcat to redeploy updated groovy changes.
Looks like application treating groovy beans as java beans.
Apart from this if I execute a groovy script without using Springs, it executes as expected. Modified groovy script changes are reflected back dynamically. Here is code for reference:
groovy-script:
package com
public class test1 {
def hello_world() {
println "Connectddded"
}
}
Main Class:
public static void main(String arg[]) {
try {
new GroovyShell().parse(newFile("test1.groovy")).invokeMethod("hello_world", null);
} catch (CompilationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
According to my understanding either we are missing something in Spring-Groovy Integration configuration that allows us to refresh back the Groovy beans modification or Tomcat is not allowing us refresh back the updated groovy script.
If someone can provide any suggesting on this would be helpful. Thanks in advance.
Regards,
Divya Garg
Thanks all, who have spent their time to read my post. Issue is resolved.
Actually we were using #component and groovy-context.xml file simultaneously because of that we were facing this issue. I have removed annotation and put my groovy file in classpath. Now everything is working file as expected. Groovy beans are getting refresh properly. But I coluld not achieve the same using spring annotations.
Now I am facing another issue and I tried a lot for it. I have another groovy bean where I have my all static methods called (GroovyConnectionHelper.groovy). I am not able to call these static methods in GroovyConnection.script. When application executes applcation get hangs on the place where execution reaches to GroovyConnectionHelper static method.
To resolve the issue I had tried to inject GroovyConnectionHelper bean in GroovyConnection as follows(Which is not good approach):
groovy-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<lang:defaults refresh-check-delay="1000"/>
<lang:groovy name="endPointManager" script-source="classpath:GroovyConnection.groovy">
<lang:property name="groovyConnectionHelper" ref="groovyConnectionHelper"/>
</lang:groovy>
<lang:groovy id="groovyConnectionHelper" script-source="classpath:GroovyConnectionHelper.groovy"/>
</beans>
And i put the setter for the same in GroovyConnection.groovy:
public void setGroovyConnectionHelper(GroovyConnectionHelper groovyConnectionHelper) {
System.out.println( "Setting ----------------------------------------- groovyConnectionHelper : " + groovyConnectionHelper );
if ( null != groovyConnectionHelper ){
System.out.println( "Object groovyConnectionHelper: ::: " + groovyConnectionHelper.dump() );
}
this.groovyConnectionHelper = groovyConnectionHelper;
}
But this is not working out. Facing this error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.scripting.groovy.GroovyScriptFactory#0': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scriptedObject.org.springframework.scripting.groovy.GroovyScriptFactory#0': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'groovyConnectionHelper' of bean class [GroovyConnection]: Bean property 'groovyConnectionHelper' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 71 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scriptedObject.org.springframework.scripting.groovy.GroovyScriptFactory#0': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'groovyConnectionHelper' of bean class [GroovyConnection]: Bean property 'groovyConnectionHelper' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.dynamic.BeanFactoryRefreshableTargetSource.obtainFreshBean(BeanFactoryRefreshableTargetSource.java:77)
at org.springframework.scripting.support.RefreshableScriptTargetSource.obtainFreshBean(RefreshableScriptTargetSource.java:79)
at org.springframework.aop.target.dynamic.BeanFactoryRefreshableTargetSource.freshTarget(BeanFactoryRefreshableTargetSource.java:66)
at org.springframework.aop.target.dynamic.AbstractRefreshableTargetSource.refresh(AbstractRefreshableTargetSource.java:97)
at org.springframework.aop.target.dynamic.AbstractRefreshableTargetSource.getTargetClass(AbstractRefreshableTargetSource.java:68)
at org.springframework.scripting.support.ScriptFactoryPostProcessor.createRefreshableProxy(ScriptFactoryPostProcessor.java:553)
at org.springframework.scripting.support.ScriptFactoryPostProcessor.postProcessBeforeInstantiation(ScriptFactoryPostProcessor.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:880)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:852)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:446)
... 79 more
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'groovyConnectionHelper' of bean class [GroovyConnection]: Bean property 'groovyConnectionHelper' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
... 94 more
Please suggest should I use Groovy Bean Injection for this or we can directely call groovy static methods direcly. Thanks in advance
Regards,
Divya Garg

How to prevent a Java EE app from starting when Spring DI fails

(I'm not sure if this question applies to Java EE apps in general or is Websphere-specific.)
When we get a Spring DI failure on apps we've deployed to WebSphere (a JNDI lookup failure, for example) the application still appears to have started successfully.
[15/02/11 17:21:22:495 GMT] 00000037 ContextLoader E org.springframework.web.context.ContextLoader initWebApplicationContext Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mybean' defined in
...big stack trace...
[15/02/11 17:21:22:526 GMT] 00000037 ApplicationMg A WSVR0221I: Application started: myapp
How can I make the application fail to start if exceptions are thrown during the spring initialisation?
Check if this helps. Based on that I'd guess it's application server-specific, but not sure.
Binding Spring context's lifecycle with an application's lifecycle should help.
Inside J2EE server Spring context is acquired mostly through the org.springframework.context.access.ContextSingletonBeanFactoryLocator (for example it is used by org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor). Invoking Spring context initialization eagerly on the application startup should do the job.
It could be done in the WebSphere specific way using Startup Beans:
#RemoteHome(AppStartUpHome.class)
#Stateless
public class SpringLifecycleBean {
private static Log logger = LogFactory.getLog(SpringLifecycleBean.class);
private static BeanFactoryReference bfr;
public boolean start() throws RemoteException {
logger.debug("Initializing spring context.");
try {
BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
//hardcoded spring context's name (refactor for more complex use cases)
bfr = bfl.useBeanFactory("appContext");
} catch (Exception e) {
logger.error("Spring context startup failed", e);
return false;
}
return true;
}
public void stop() throws RemoteException {
if (bfr != null) {
logger.debug("Releasing spring context.");
bfr.release();
}
}
}
Adding a webapp module with javax.servlet.ServletContextListener containing similar code will also work.

Resources