Tomcat doesn't start with BIRT servlet - java

I don't have much experience with Java and I need a little help with the following issue.
I’m trying to make a Birt Java Servlet in order to generate PDF files based on a given input (XML in this case). I’m using Tomcat 7.0 for that I was able to create blank PDF files with this code (I’ve commented out a lot of lines in order to get Tomcat started).
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//get report name and launch the engine
resp.setContentType( "application/pdf" );
resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
String reportName = req.getParameter("ReportName");
ServletContext sc = req.getSession().getServletContext();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
But when I try with the complete code that is:
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
private IReportEngine birtReportEngine = null;
protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//get report name and launch the engine
resp.setContentType( "application/pdf" );
resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
String reportName = req.getParameter("ReportName");
ServletContext sc = req.getSession().getServletContext();
this.birtReportEngine = BirtEngine.getBirtEngine(sc);
IReportRunnable design;
try
{
//Open report design
design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
//create task to run and render report
IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );
task.getAppContext().put("BIRT_VIEWER_HTTPSERVLET_REQUEST", req );
PDFRenderOption options = new PDFRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
options.setOutputStream(resp.getOutputStream());
task.setRenderOption(options);
//run report
task.run();
task.close();
}catch (Exception e){
e.printStackTrace();
throw new ServletException( e );
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
the Tomcat Server (Version 7.0) doesn’t start anymore and the following info is logged to the console:
Nov 17, 2017 11:09:44 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/test_servlet]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1239)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/test_servlet]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
... 6 more
Caused by: java.lang.NoClassDefFoundError: org/eclipse/birt/report/engine/api/IRenderOption
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:270)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:139)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:417)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:891)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:388)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5519)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.birt.report.engine.api.IRenderOption
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
... 20 more
Nov 17, 2017 11:09:44 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1239)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:444)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:758)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.startup.Catalina.start(Catalina.java:694)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:294)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:428)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1247)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 6 more
Nov 17, 2017 11:09:44 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.startup.Catalina.start(Catalina.java:694)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:294)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:428)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:758)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:444)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1247)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 11 more
Nov 17, 2017 11:09:44 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
Nov 17, 2017 11:09:44 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
Nov 17, 2017 11:09:44 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
Nov 17, 2017 11:09:44 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
Nov 17, 2017 11:09:44 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]
Any help or example of a working Birt servlet would be apreciated.
Thanks in advance!

Related

Spring Boot - Failed to initialize ServletRegistrationBean in WebLogic 12c

We're running GraphQL sample Java application in WebLogic 12c, but encountered some errors with servlet during startup.
The servlet was configured and register our servlets using a ServletRegistrationBean as below:
#Configuration
#ConditionalOnWebApplication
#ConditionalOnClass(DispatcherServlet.class)
#ConditionalOnBean({GraphQLSchema.class, GraphQLSchemaProvider.class})
#ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, SpringGraphQLCommonAutoConfiguration.class})
#EnableConfigurationProperties(GraphQLServletProperties.class)
public class GraphQLWebAutoConfiguration {
...
#Bean
#ConditionalOnMissingBean
public GraphQLServlet graphQLServlet(GraphQLSchemaProvider schemaProvider, ExecutionStrategyProvider executionStrategyProvider) {
return new SimpleGraphQLServlet(schemaProvider, executionStrategyProvider, listeners, instrumentation, errorHandler, contextBuilder);
}
#Bean
ServletRegistrationBean graphQLServletRegistrationBean(GraphQLServlet servlet) {
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, graphQLServletProperties.getServletMapping());
bean.setLoadOnStartup(1);
return bean;
}
}
In the weblogic server log, it prints out errors:
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101125> <[ServletContext#933807824[app:CPRES module:CPRES path:null spec-version:3.1]] Error occurred while instantiating servlet: "simpleGraphQLServlet".
java.lang.InstantiationException: graphql.servlet.SimpleGraphQLServlet
at java.lang.Class.newInstance(Class.java:427)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.newServletInstanceIfNecessary(StubSecurityHelper.java:365)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoSuchMethodException: graphql.servlet.SimpleGraphQLServlet.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101216> <Servlet: "simpleGraphQLServlet" failed to preload on startup in Web application: "CPRES".
javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:326)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:29 PM SGT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "19094957742917053" for task "130" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated"
weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
It looks that the weblogic is trying to create a new servlet instance instead of the ServletBean SimpleGraphQLServlet created and managed by Spring context.
Any advance? Thanks.
A walkaround solution is to write a Servlet wrapper class like this:
public class DelegateGraphQLServlet extends HttpServlet {
protected GraphQLServlet graphQLServlet;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ApplicationContext ac = (ApplicationContext) servletConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.graphQLServlet = (GraphQLServlet)ac.getBean("graphQLServlet");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
graphQLServlet.service(req, res);
}
}

ScheduledExecutorService Thread creating multiples threads

I'm facing a wrong behavior using ScheduledExecutorService due a restart mechanism implemented.
Problem - Short
Each restart attempt is creating a new Scheduled task and restarting the old ones.
Problem - Long
The process goal is to publish a message into RabbitMQ from time to time ( it's keep-alive ). When an exception occurs with RabbitMQ, it uses the ExceptionObserver to notify
that an exception occurred. The ExceptionObserver implemented stops the service and restart it again. It attemp to restart 3 times, if it was restart succesfully, the count is
reseted to zero. If it couldn't restart, the attempt count is incremented and if it reaches the attempt limit, it will shutdown the process.
Each time the service is restarted, it creates a new "KeepAliveService" and restarts the last service. So, each time an exception occours, a new service is created and the old
service is restarted. If 1 exception occours after restart there are 2 process running. If 2 exception occours there are 3 process running, and so on.
The service class which handles the keep-alive service ( start/stop ScheduledExecutorService )
private KeepaliveExecutor keepaliveExecutor; // This is the runnable used inside the scheduledService
private ScheduledFuture futureTask; // The escheduled task
private ScheduledExecutorService scheduledService; // the scheduled service
private ExceptionObserver exceptionObserver; // The Exception Handler, which will handle the exceptions
public void startService( final int keepaliveTime ) throws IllegalArgumentException, FInfraException {
keepaliveExecutor = new KeepaliveExecutor( new RabbitMQService( settings ), settings );
keepaliveExecutor.setExceptionObserver( exceptionObserver );
scheduledService = Executors.newSingleThreadScheduledExecutor();
futureTask = scheduledService.scheduleAtFixedRate( keepaliveExecutor, 0, keepaliveTime, TimeUnit.MINUTES );
}
public void stopService() {
futureTask.cancel(true);
scheduledService.shutdown();
}
The KeepaliveExecutor class
class KeepaliveExecutor implements Runnable {
private FInfraExceptionObserver exceptionObserver;
#Override
public void run() {
try {
final String keepAlive = JsonMapper.toJsonString( keepaliveMessage );
rabbitService.publishMessage( keepAlive );
keepaliveMessage.setFirtsPackage( false );
} catch( FInfraException ex ) {
if( exceptionObserver != null ) {
exceptionObserver.notifyExpcetion(ex);
}
}
}
The ExceptionObserver implementation class
public class FInfraExceptionHandler implements FInfraExceptionObserver {
private final FInfraServiceHandler finfraHandler;
public FInfraExceptionHandler(FInfraServiceHandler finfraHandler) {
this.finfraHandler = finfraHandler;
}
#Override
public void notifyExpcetion(Throwable ex) {
Util.logger.log( Level.INFO, "F-Infra Exception occurred", ex);
finfraHandler.stopService();
Util.logger.log( Level.INFO, "Waiting 30s for restarting..." );
Util.wait( 30, TimeUnit.SECONDS );
finfraHandler.startService();
}
The FInfraServiceHandler class
public class FInfraServiceHandler {
private static final int ATTEMPT_LIMIT = 3;
private FInfraService finfraService;
private int keepaliveTime;
private int attempt;
public FInfraServiceHandler() {
this.finfraService = new FInfraService();
this.finfraService.setExceptionObserver(new FInfraExceptionHandler( this ));
this.attempt = 0;
}
void startService(){
if( attempt <= ATTEMPT_LIMIT ) {
try {
attempt++;
Util.logger.log(Level.INFO, "Starting F-Infra Service. Attemp[{0} of {1}]", new String[]{String.valueOf(attempt), String.valueOf(ATTEMPT_LIMIT)});
finfraService.startService( keepaliveTime );
} catch( FInfraException | RuntimeException ex ){
Util.logger.log(Level.INFO, "F-INFRA EXCEPTION", ex);
startService();
}
Util.logger.log( Level.INFO, "F-Infra started!");
attempt = 0;
return;
}
Util.logger.log( Level.INFO, "Restart attemp limit reached." );
Main.closeAll(new ShutdownException("It's not possible stablish a connection with F-Infra Service."));
}
public void stopService() {
if( attempt > 0 ){
Util.logger.log(Level.INFO, "Stpoping F-Infra...");
finfraService.stopService();
}
}
And here follows the log which tells me there are more than one service running
jul 16, 2017 2:58:03 PM domain.FInfraServiceHandler startService
INFO: Starting F-Infra Service. Attemp[1 of 3]
jul 16, 2017 2:58:03 PM domain.FInfraServiceHandler startService
INFO: F-Infra started!
jul 16, 2017 5:01:15 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: F-Infra Exception occurred
domain.FInfraException: java.net.UnknownHostException: rabbit.domain
at domain.RabbitMQService.openConnection(RabbitMQService.java:48)
at domain.RabbitMQService.publishMessage(RabbitMQService.java:66)
at domain.KeepaliveExecutor.run(KeepaliveExecutor.java:38)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.UnknownHostException: rabbit.domain
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:34)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:91)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:670)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
at domain.RabbitMQService.openConnection(RabbitMQService.java:45)
... 9 more
jul 16, 2017 5:01:15 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: Waiting 30s for restarting...
jul 16, 2017 5:01:45 PM domain.FInfraServiceHandler startService
INFO: Starting F-Infra Service. Attemp[1 of 3]
jul 16, 2017 5:01:45 PM domain.FInfraServiceHandler startService
INFO: F-Infra started!
jul 16, 2017 6:01:58 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: F-Infra Exception occurred
domain.FInfraException: java.net.UnknownHostException: rabbit.domain
at domain.RabbitMQService.openConnection(RabbitMQService.java:48)
at domain.RabbitMQService.publishMessage(RabbitMQService.java:66)
at domain.KeepaliveExecutor.run(KeepaliveExecutor.java:38)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.UnknownHostException: rabbit.domain
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:34)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:91)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:670)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
at domain.RabbitMQService.openConnection(RabbitMQService.java:45)
... 9 more
jul 16, 2017 6:01:58 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: Waiting 30s for restarting...
jul 16, 2017 6:02:03 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: F-Infra Exception occurred
domain.FInfraException: java.net.UnknownHostException: rabbit.domain
at domain.RabbitMQService.openConnection(RabbitMQService.java:48)
at domain.RabbitMQService.publishMessage(RabbitMQService.java:66)
at domain.KeepaliveExecutor.run(KeepaliveExecutor.java:38)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.UnknownHostException: rabbit.domain
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:34)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:91)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:670)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
at domain.RabbitMQService.openConnection(RabbitMQService.java:45)
... 9 more
jul 16, 2017 6:02:03 PM domain.FInfraExceptionHandler notifyExpcetion
INFO: Waiting 30s for restarting...
jul 16, 2017 6:02:28 PM domain.FInfraServiceHandler startService
INFO: Starting F-Infra Service. Attemp[1 of 3]
jul 16, 2017 6:02:28 PM domain.FInfraServiceHandler startService
INFO: F-Infra started!
jul 16, 2017 6:02:33 PM domain.FInfraServiceHandler startService
INFO: Starting F-Infra Service. Attemp[1 of 3]
jul 16, 2017 6:02:33 PM domain.FInfraServiceHandler startService
INFO: F-Infra started!
I don't know what to do to close the old Thread or use the current one to restart. What I tried wast calling Thread.currentThread().interrupt(); on the ExceptionObserver class before calling start method.
But that doesn't works.
I have no idea in what to do.
In the FInfraServiceHandler class, your stopService method does not do anything if attempt is zero.
public void stopService() {
if( attempt > 0 ){
Util.logger.log(Level.INFO, "Stpoping F-Infra...");
finfraService.stopService();
}
}
So the original ScheduledExecutorService keeps going. When I removed the condition, the code behaved fine.
Note, by the way, that you call startService and stopService on the same instance, from different threads. I think you'll need some sort of synchronization on the mutable field attempt.

java.lang.IllegalStateException when run spring java based configuration?

When I try to run Spring java annotation based configuration I get that exception trace
Sep 28, 2014 10:24:38 PM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh INFO: Refreshing
org.springframework.context.annotation.AnnotationConfigApplicationContext#20ad9418:
startup date [Sun Sep 28 22:24:38 EET 2014]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Cannot
load configuration class: com.learn.HelloWorldConfig at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:378)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
at
org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at com.learn.MainApp.main(MainApp.java:9) Caused by:
org.springframework.cglib.core.CodeGenerationException:
java.lang.reflect.InvocationTargetException-->null at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:237)
at
org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at
org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:128)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:368)
... 6 more Caused by: java.lang.reflect.InvocationTargetException at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483) at
org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:384)
at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219)
... 11 more Caused by: java.lang.SecurityException: class
"com.learn.HelloWorldConfig$$EnhancerBySpringCGLIB$$3f39adab"'s signer
information does not match signer information of other classes in the
same package at
java.lang.ClassLoader.checkCerts(ClassLoader.java:895) at
java.lang.ClassLoader.preDefineClass(ClassLoader.java:665) at
java.lang.ClassLoader.defineClass(ClassLoader.java:758) ... 17 more
HelloWorld.java
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
HelloWorldConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
MainApp.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HelloWorldConfig.class);
ctx.refresh();
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
ctx.close();
System.out.println("Test");
}
}
Why I get that exception ?

Null point always

It all ways passing null point after this line, System.out.println("Inside the filter.............." ); so can anyone tell me what's wrong in my code and logic
and home.jsp(index page) did not display. here I want to filter every url and proceed only valid login users requests. here my logic..
UserServlet.java
private void loginDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
User u = new User();
UserService us =new UserServiceImpl() ;
String Uname = request.getParameter("txtUname");
String Pwrd = request.getParameter("txtPwrd");
u.setUname(Uname);
u.setPwrd(Pwrd);
System.out.println(Uname+""+Pwrd);
try {
if(us.Userlogin(u.getUname(),u.getPwrd())){
String message = "Thank you, " + Uname +"..You are now logged into the system";
request.setAttribute("message", message);
//RequestDispatcher rd = getServletContext().getRequestDispatcher("/menu.jsp");
//rd.forward(request, response);
HttpSession session = request.getSession(true);
session.setAttribute("loggedUser", u);
String reqUrl = (String)session.getAttribute("requestedURL");
session.removeAttribute("requestedURL");
response.sendRedirect(reqUrl);
}else{
// direct to login}
FilterRequest.java
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("Inside the filter.............." );
HttpSession session = request.getSession(true);
User u = null;
if(session.getAttribute("loggedUser")!=null){
u = (User) session.getAttribute("loggedUser");
}
if (u!= null)
{
System.out.println("user does exits.." + u.getUname() );
chain.doFilter(req, resp);
}else{
String message = "Please Login!";
req.setAttribute("loginMsg", message);
//response.sendRedirect("login2.jsp");
}
}
web.xml
<filter>
<filter-name>FilterRequest</filter-name>
<filter-class>com.mobitel.bankdemo.web.FilterRequest</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterRequest</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
stack trace
`Jul 11, 2013 10:24:26 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Kaspersky Lab\Kaspersky Anti-Virus 6.0 for Windows Workstations MP4\;C:\Program Files\Java\jdk1.6.0_07/bin;C:\Program Files\MySQL\MySQL Server 5.2\bin;D:\common libs\com.mysql.jdbc_5.1.5.jar;;C:\Users\lcladmin\Documents\Softwares\java related\eclipse-jee-indigo-win32_2\eclipse;
Jul 11, 2013 10:24:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:BankDemoWeb' did not find a matching property.
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Jul 11, 2013 10:24:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 554 ms
Jul 11, 2013 10:24:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jul 11, 2013 10:24:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.41
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Jul 11, 2013 10:24:27 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 517 ms
Inside the filter..............
user does exits..`
Thank you..
You have a real simple problem: The user is not logged in ;)
To clarify things:
In you Filter you're checking if the user is logged in and in this case execute the chain with
chain.doFilter(req, resp);
That's fine so far.
But what happens if the user is not logged in? In this case you're not executing the chain and therefore no Servlet. The Servlet is always the last element in the chain.
So your users cannot log in as they never get to the Servlet that allows them to log in as you filter them out before.
You have to extend your filter to allow logins when no user is logged in. This can be done e.g. by changing the url-pattern of the Filter.

Tomcat 7 crashes on startup when using JExcel Api in webapp

I'm trying to export data from a database into an Excelsheet using the JExcel Api when a specific servlet is called, but when starting Tomcat I get multiple exceptions. Here's the error message as given by eclipse:
Nov 01, 2012 10:57:14 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/web]]
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:785)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/web]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 7 more
Caused by: java.lang.NoClassDefFoundError: jxl/write/WriteException
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:87)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:140)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:67)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: java.lang.ClassNotFoundException: jxl.write.WriteException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
... 21 more
Nov 01, 2012 10:57:14 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:451)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:785)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Nov 01, 2012 10:57:14 AM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:451)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
Here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.write.WriteException;
/**
* Servlet implementation class Test
*/
#WebServlet(description = "A simple test.", urlPatterns = { "/test" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Test() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
WriteExcel.writeTestFile();
} catch (WriteException e) {
e.printStackTrace();
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Test!</title>");
out.println("</head>");
out.println("<body>");
out.println("I've written an Excel file!");
out.println("</body>");
out.println("</html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here is the code of the WriteExcel class:
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
//tomcat hat probleme mit der jxl library
public class WriteExcel {
private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private String inputFile;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet);
workbook.write();
workbook.close();
}
private void createLabel(WritableSheet sheet)
throws WriteException {
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// Create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
cv.setFormat(timesBoldUnderline);
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "Header 1");
addCaption(sheet, 1, 0, "This is another header");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
// Write a few number
for (int i = 1; i < 10; i++) {
// First column
addNumber(sheet, 0, i, i + 10);
// Second column
addNumber(sheet, 1, i, i * i);
}
// Lets calculate the sum of it
StringBuffer buf = new StringBuffer();
buf.append("SUM(A2:A10)");
Formula f = new Formula(0, 10, buf.toString());
sheet.addCell(f);
buf = new StringBuffer();
buf.append("SUM(B2:B10)");
f = new Formula(1, 10, buf.toString());
sheet.addCell(f);
// Now a bit of text
for (int i = 12; i < 20; i++) {
// First column
addLabel(sheet, 0, i, "Boring text " + i);
// Second column
addLabel(sheet, 1, i, "Another text");
}
}
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
private void addLabel(WritableSheet sheet, int column, int row, String s)
throws WriteException, RowsExceededException {
Label label;
label = new Label(column, row, s, times);
sheet.addCell(label);
}
public static void writeTestFile() throws WriteException, IOException {
WriteExcel test = new WriteExcel();
test.setOutputFile("d:/test.xls");
test.write();
System.out.println("Please check the result file under d:/test.xls");
}
}
The method writeTestFile() from the WriteExcel class works fine when tested in a local standalone project.
The servlet itself also works when the method writeTestFile() is not called.
Could someone clarify why I'm getting the exceptions?
Also is there a fix or workaround?
Try this: double click on the server, click on "Open launch configuration", go to Classpath tab and under User Entries add the jar.

Categories

Resources