Using RMI with JSF and Tomcat - java

I want to write a simple application using RMI. On the server side I have an interface foo and a class fooImpl.
My interface is:
import java.rmi.Remote;
public interface Foo extends Remote {
public String exec(String test) throws Exception;
}
My implementation of the the above interface is:
import java.rmi.server.UnicastRemoteObject;
public class FooImpl extends UnicastRemoteObject implements Foo {
public FooImpl() throws Exception {
java.rmi.registry.LocateRegistry.createRegistry(1099);
java.rmi.Naming.rebind("myFoo",this);
}
public String exec(String test) {
return "This is a Test";
}
public static void main(String[] args) {
try {
FooImpl fooImpl = new FooImpl();
} catch (Exception e) {
e.printStackTrace();
}
}
}
On the client side, I have web application using PrimeFace which is runnig on Tomcat. There is a IndexBean on client side:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
#ManagedBean
#RequestScoped
public class IndexBean {
public void execute() {
try {
Foo foo = (Foo) java.rmi.Naming.lookup("//localhost/myFoo");
System.out.println(foo.exec());
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
when I execute the code, I get the following error at the client side:
java.rmi.UnmarshalException: error unmarshalling return; nested
exception is: java.lang.ClassNotFoundException: Foo (no security
manager: RMI class loader disabled) at
sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source) at
java.rmi.Naming.lookup(Naming.java:101) at
bean.IndexBean.execute(IndexBean.java:15) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
org.apache.el.parser.AstValue.invoke(AstValue.java:245) at
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at
org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
at
javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:88)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:51)
at
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:409)
at javax.faces.component.UICommand.broadcast(UICommand.java:103) at
javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1013)
at
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:284)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1302)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:745)
at
org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:38)
at
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
at
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744) Caused by:
java.lang.ClassNotFoundException: Foo (no security manager: RMI class
loader disabled) at
sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:553)
at
java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:646)
at
java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:311)
at
sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:255)
at
java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1558)
at
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
... 44 more
Also, I changed the port which Tomcat uses to do not have conflict with RMI port.

The client doesn't have the remote interface on its CLASSPATH, or, probably, the stub either. To avoid using a stub, add
super(0);
as the first line of the constructor.
NB you must store the result of createRegistry() in a static variable, to prevent the Registry from exiting.

Related

#EJB annotation causes servlet to stop working

I have the following EJB implementing a simple ActiveMQ message enqueue. The ActiveMQ code itself works just fine. This is being deployed on a TomEE server.
SenderBean class:
package Beans;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
#LocalBean
#Stateless
public class SenderBean {
private ConnectionFactory factory = null;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private MessageProducer producer = null;
public SenderBean() {
}
public void sendMessage() {
try {
factory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("SAMPLEQUEUE");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText("Hello ...This is a sample message..sending from FirstClient");
producer.send(message);
System.out.println("Sent: " + message.getText());
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
I also have the following class which tries to use the bean in a servlet. If I include the #EJB annotation, like in the following example, the servlet throws an exception upon receiving post. However, if i remove the annotation and instantiate the bean class with new SenderBean(), everything works as it should. What could be the cause of this?
SenderServlet class:
package Servlets;
import Beans.ReceiverBean;
import Beans.SenderBean;
import javax.ejb.EJB;
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 java.io.IOException;
#WebServlet(name = "SenderServlet")
public class SenderServlet extends HttpServlet {
#EJB
SenderBean senderBean;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
senderBean.sendMessage();
}
}
The exception being received in the HttpServletResponse after a 500 error:
HTTP Status 500 - Error instantiating servlet class Servlets.SenderServlet</h1><div class="line"></div><p><b>type</b> Exception report</p><p><b>message</b> <u>Error instantiating servlet class Servlets.SenderServlet</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b></p><pre>javax.servlet.ServletException: Error instantiating servlet class Servlets.SenderServlet
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause javax.naming.NameNotFoundException: Name [Servlets.SenderServlet/senderBean] is not bound in this Context. Unable to find [Servlets.SenderServlet].
org.apache.naming.NamingContext.lookup(NamingContext.java:816)
org.apache.naming.NamingContext.lookup(NamingContext.java:173)
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
The exploded artifact:
don't you have a classpath clash with activemq or hibernate? are the provided library NOT in WEB-INF/lib?

Error with passing this JSON with nested list of objects to a rest controller in spring

Please i am trying to pass this json to a controller in spring framework.
{
"date" : "2012-02-09",
"subject" : "Margin ",
"selections" : [
{"FGY" : ["Try", "Harder"]},{"LGY" : ["Harder", "Try"]}
]
}
The Selections Class is
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
#Component
public class Selections implements Serializable {
//#Bean
public Selections(){
}
#JsonProperty("FGY")
private List<String> FGY;
#JsonProperty("LGY")
private List<String> LGY;
public List<String> getFGY() {
return FGY;
}
public void setFGY(List<String> FGY) {
this.FGY = FGY;
}
public String getLGY(){
return LGY;
}
public void setLGY(List<String> LGY) {
this.LGY = LGY;
}
}
The ReportRequest Class is :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
#Component
public class ReportRequest implements Serializable{
private String report;
private Date date;
private List<Selections> selections;
public ReportRequest(){
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<Selections> getSelections() {
return selections;
}
public void setSelections(List<Selections> selections) {
this.selections = selections;
}
public ReportResponse processRequest() {
for(Selections selection : getSelections()){ // null error occurs on either FGY or LGY depending on which is the second in the json list
selection.getFGY().forEach(System.out::println);
selection.getLGY().forEach(System.out::println);
}
return null;
}
The controller
#RequestMapping(value = "/request_report" , method = RequestMethod.POST )
public #ResponseBody
ReportResponse receive(#RequestBody ReportRequest reportRequest) {
return reportRequest.processRequest();
}
This is the error : java.lang.NullPointerException: null
Doing a debug i was able to find out that the null error occurs in the ReportRequest processRequest method.
OLD ERROR(SOLVED): The other attributes of the reportRequest object were properly initialized from the json but the attribute "selections" failed to initialize the "FGY" object with the list of strings in the json
EDIT(NEW ERROR): The new error is, only the first object in the selections list in the json is passed into the selections list in spring class ReportRequest. The second object in the list is not passed. Thus the null error occurs on whichever is second in the json. eg LGY is second presently.
StackTrace :
`
java.lang.NullPointerException: null
at com.teamapt.alm.utils.ReportRequest.processRequest(ReportRequest.java:79)
at com.teamapt.alm.controller.AlmController.receive(AlmController.java:66)
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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.teamapt.alm.config.Config$1.doFilter(Config.java:36)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Give the getter/setter combo
public List<String> getFGY() {
return FGY;
}
public void setFGY(List<String> FGY) {
this.FGY = FGY;
}
Jackson (which I assume is what you are using for your JSON serialization/deserialization) will determine the property's name to be fgy, not FGY. Deserialization will therefore not find your property.
You can annotate either one with
#JsonProperty("FGY")
to explicitly set the property name you expect.
Try using #JsonIgnore in the child class on parents collection. It is trying to serialize recursively.
Follow this link for other ways to handle this.

java.lang.IllegalStateException servlet exception when download file from web server

I have some code for download file from web server.
Everything works alright, but in console I have this exception:
июн 26, 2015 2:08:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/TestTask] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:462)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:109)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:57)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:909)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:576)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Why and what it can be? And how i can fix this problem? I try find answer in the google, but I failed.
The code:
package actions;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import org.apache.log4j.Logger;
import org.apache.struts.chain.contexts.ServletActionContext;
import service.CsvCreator;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadCsvAction extends ActionSupport {
private static final long serialVersionUID = -4714537109287679996L;
private CsvCreator CSVcreator;
private static final Logger logger = Logger.getLogger(DownloadCsvAction.class);
public CsvCreator getCSVcreator() {
return CSVcreator;
}
public void setCSVcreator(CsvCreator cSVcreator) {
CSVcreator = cSVcreator;
}
#Override
public String execute() {
HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment; filename=\"phone_records.csv\"");
response.setContentType("text/csv");
ServletOutputStream out;
try {
out = response.getOutputStream();
String tableHeader = "Caller, Event, Reciever, Timestamp\n";
out.write(tableHeader.getBytes("UTF-8"));
out.write(CSVcreator.getAllRecordsInString().getBytes("UTF-8"));
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return SUCCESS;
}
}
And my struts.xml:
<action name="DownloadCsvAction" class="DownloadCsvAction">
<result name="success" type="dispatcher"/>
</action>
Why and what it can be?
Because response is already committed. You have closed response before it's used by the Struts2.
And how I can fix this problem?
When your action execution ends, return Action.NONE result code. This code tells the invoker to not execute any result because response might be already committed.
You can also rewrite the action implementation to use stream result type. In this way you have not to do with the response and let Struts2 do the rest. Example of using stream result is here.

Jersey - get remote address inside ContainerRequestFilter scope

I was trying to use the code of this question and everytime I make a request to the application I get this error:
HTTP Status 500 - Servlet.init() for servlet api.tienda.venta.ApplicationConfig threw exception
Stack trace:
javax.servlet.ServletException: Servlet.init() for servlet api.tienda.venta.ApplicationConfig threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
This is the code that I'm using:
//ApplicationConfig.java
#ApplicationPath("venta")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(JacksonFeature.class);
resources.add(RequestFilter.class);
resources.add(api.tienda.venta.ventaResource.class);
}
}
// RequestFilter.java
public class RequestFilter implements ContainerRequestFilter{
#Context
private HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext) {
String remoteAddr = request.getRemoteAddr();
System.out.print("Remote Address: " + remoteAddr);
}
}
If I remove the #Context annotation the error is gone and everything works normally, any clue about what is happening here?

Java SQL ResultSet Exception

I'm Developing a Web Application using JSF & PrimeFaces. I have two classes Inputs & DBConn. And i'm executing a SQL command like this
SQL="SELECT COUNT(*) FROM TXN_HEADER WHERE REQUEST_DATE='01-AUG-2014'"
And then in the DBConn class i call the next() method on the ResultSet object inside a while loop condition to print the result.
This works fine and gives me an output.
But when i try to call that ResultSet object to get an output using the same scenario above (using that while loop inside the Inputs class) it gives me the following exception.
java.sql.SQLException: Result set after last row
at oracle.jdbc.driver.GeneratedScrollableResultSet.getString(GeneratedScrollableResultSet.java:879)
at Inputs.commandButton(Inputs.java:41)
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.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Then i assumed that after the first use of the next() method the cursor is still in the end though i used the next() method again in that Inputs class.
So i tried using the .beforeFirst() method before going to the 2nd while loop to reset the cursor back to the top. But it gave me the same error again.
Then i tried commenting the 1st while loop i access in the DBConn class so the cursor is at the top for sure. But then it gives me the following error.
java.sql.SQLException: ResultSet.next was not called
at oracle.jdbc.driver.GeneratedScrollableResultSet.getString(GeneratedScrollableResultSet.java:874)
at Inputs.commandButton(Inputs.java:41)
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.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
How do i resolve this? This is my first time developing a Database Application.
And sorry about these bunch of sys.prints, I used them for debugging.
These are the two classes related to this case:
Inputs Class
import java.sql.SQLException;
import javax.annotation.ManagedBean;
#ManagedBean
public class Inputs {
private String date;
private String showRes;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getShowRes() {
return showRes;
}
public void setShowRes(String showRes) {
this.showRes=showRes;
}
public void commandButton(){
DBConn nCon=new DBConn();
Calculations nCalc=new Calculations();
nCalc.setPieChartSQL(getDate());
nCon.setSQL(nCalc.getPieChartSQL());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
try {
System.out.println(nCon.getResultSet().getString(1));
//nCon.getResultSet().beforeFirst();
while(nCon.getResultSet().next()){
System.out.println("++++++++++++");
System.out.println(nCon.getResultSet().getString(1));
System.out.println("++++++++++++");
setShowRes(nCon.getResultSet().getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("777777777777777777777");
}
}
DBConn Class
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleDataSource;
public class DBConn {
private String sql;
private ResultSet rs;
public ResultSet getResultSet(){
try {
OracleDataSource dataSource=new OracleDataSource();
dataSource.setURL("jdbc:oracle:thin:#172.16.20.45:1521:ABS");
dataSource.setUser("<user>");
dataSource.setPassword("<pass>");
OracleConnection con = (OracleConnection)dataSource.getConnection();
con.setAutoCommit(false);
Statement stmnt = con.createStatement();
rs = stmnt.executeQuery(sql);
System.out.println("-----------");
System.out.println(rs);
System.out.println("-----------");
System.out.println(rs);
System.out.println("-----------");
while(rs.next()){
System.out.println("*************");
System.out.println(rs.getString(1));
System.out.println("*************");
}
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void setSQL(String sql) {
this.sql=sql;
}
}
I think the problem is in the way you get the resultset. Each time you call nCon.getResultSet() it returns a new resultset. That means you call next method of one resultset object and calls getString(1) in another. Here is my solution.
public void commandButton(){
DBConn nCon=new DBConn();
Calculations nCalc=new Calculations();
nCalc.setPieChartSQL(getDate());
nCon.setSQL(nCalc.getPieChartSQL());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
try {
ResultSet rst=nCon.getResultSet();
rst.beforeFirst();
while(rst.next()){
System.out.println("++++++++++++");
String str=rst.getString(1);
System.out.println("++++++++++++");
setShowRes(str);
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("777777777777777777777");
}
Your getResultMethod() is putting cursor at the end of the ResultSet. And this Exception occurs because you are not calling next() and trying to access the ResultSet in your below method
public void commandButton(){
DBConn nCon=new DBConn();
Calculations nCalc=new Calculations();
nCalc.setPieChartSQL(getDate());
nCon.setSQL(nCalc.getPieChartSQL());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
System.out.println(nCon.getResultSet());
System.out.println("............");
try {
System.out.println(nCon.getResultSet().getString(1)); //here rs.next() should be called first
//nCon.getResultSet().beforeFirst();
while(nCon.getResultSet().next()){
System.out.println("++++++++++++");
System.out.println(nCon.getResultSet().getString(1));
System.out.println("++++++++++++");
setShowRes(nCon.getResultSet().getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("777777777777777777777");
}
Solution
try{
while(rs.next()){
System.out.println(nCon.getResultSet().getString(1));
}
......
}

Categories