How to override CXF AbstractInvoker? - java

I've requirement where in my input request I'm getting parameters which are password thats needs to be masked Since I've kept logging level as debug, the input xml is getting logged with password fields. I fixed this problem by overriding LogginginInterceptors and LoggingOutInterceptor.
However on further analysis, found that Abstract invoker is printing method invoked along with parameters for the method invoked. Hence password field is again getting printed. I can override the method which prints parameter. But where and how I need to register my my custom abstractmethod invoker.
2014-04-03 20:16:54,827 [http-8443-1] DEBUG o.a.c.s.invoker.AbstractInvoker - Invoking method public com.kp.schema.CredResObject com.kp.CredentialsImpl.updateCredentials(com.kp.schema.CredReqObject) throws com.kp.FaultResponse on object com.kp.CredentialsImpl#2ee4e8 with params [CredReqObject [clientID=kpid, host=asda, userName=u1, passWord=sssss]].
Custom Invoker
public class NMSCustomInvoker extends AbstractInvoker {
static final ResourceBundle BUNDLE = BundleUtils
.getBundle(FactoryInvoker.class);
private Factory factory;
public NMSCustomInvoker(Factory factory) {
this.factory = factory;
}
public NMSCustomInvoker() {
}
public void setFactory(Factory f) {
this.factory = f;
}
#Override
public Object getServiceObject(Exchange ex) {
try {
return factory.create(ex);
} catch (Fault e) {
throw e;
} catch (Throwable e) {
throw new Fault(new Message("CREATE_SERVICE_OBJECT_EXC", BUNDLE), e);
}
}
public void releaseServiceObject(final Exchange ex, Object obj) {
factory.release(ex, obj);
}
#Override
protected Object performInvocation(Exchange exchange,
final Object serviceObject, Method m, Object[] paramArray)
throws Exception {
paramArray = insertExchange(m, paramArray, exchange);
return m.invoke(serviceObject, paramArray);
}
}
I'm getinng null pointer error since factory object is null.
Updated StackTrace
org.apache.cxf.interceptor.Fault: Could not instantiate service object.
at mypackage.NMSCustomInvoker.getServiceObject(NMSCustomInvoker.java:45) ~[NMSCustomInvoker.class:na]
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:50) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:94) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) [cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:248) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:222) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:153) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:167) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:211) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [servlet-api-3.0-alpha-1.jar:3.0-alpha-1]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) [catalina.jar:6.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) [catalina.jar:6.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [catalina.jar:6.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) [catalina.jar:6.0.37]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) [tomcat-coyote.jar:6.0.37]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) [tomcat-coyote.jar:6.0.37]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) [tomcat-coyote.jar:6.0.37]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_32]
Caused by: java.lang.NullPointerException: null
at mypackage.NMSCustomInvoker.getServiceObject(NMSCustomInvoker.java:41) ~[NMSCustomInvoker.class:na]
... 26 common frames omitted

You can set the invoker yourself if you are using cxf-jaxws or cxf-jaxrs front end API, just like this
ServerFactoryBean.setInvoker(new MyInvoker());
If you are using spring configuration, you can set your custom invoker just like this
<jaxws:endpoint id="simpleWithBinding"
implementor="#greeter"
address="http://localhost:8080/simpleWithAddress">
<jaxws:invoker>
<bean id="myInvoker" class="com.example.MyInvoker"/>
</jaxws:invoker>
</jaxws:endpoint>

Related

How can I make JNDI Registry thread safe?

I have a class which creates the camel routes dynamically.
Previously it creates routes through a simple loop, But now I want to make sure all routes are start at the same time. For that I used FutureTask.
Now I got the exception,
java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only
There is a JNDI registry used in CreateCamelRoute class.
whenever trying to bind object to that, it throws the exception.
How can I make JNDI Registry thread safe?
public StartRoutes(){
List<DestinationTransport> transport = findAll();
FutureTask[] randomNumberTasks = new FutureTask[transport.size()];
for (int i = 0; i < transport.size(); i++) {
Callable callable = new CallableExampleDT(transport.get(i));
randomNumberTasks[i] = new FutureTask(callable);
Thread t = new Thread(randomNumberTasks[i]);
t.start();
}
for (int i = 0; i < transport.size(); i++) {
System.out.println(randomNumberTasks[i].get());
messages.add((String) randomNumberTasks[i].get());
}
}
}
CallableExampleDT
public class CallableExampleDT implements Callable<Object> {
private final Object transport;
public CallableExampleDT(Object transport) {
this.transport = transport;
}
public synchronized Object call() throws Exception {
String status = "";
DestinationTransport t= (DestinationTransport) transport;
try {
route.createRoute(t);
} catch (Exception e) {
e.printStackTrace();
}
Thread.sleep(5000);
if (route.checkRoute(t.id()))
status= LoggingMessage.STARTED;
else
status= LoggingMessage.IS_STOPPED;
return status;
}
AsyncCamelDynamicFTPRoute
public class AsyncCamelDynamicFTPRoute{
DefaultCamelContext defaultCamelContext = null;
private CamelContext context = null;
JndiRegistry jndi = new JndiRegistry();
public synchronized void createRoute(Object object) throws ApplicationException {
DestinationTransport dt= (DestinationTransport) object;
String destinationTransport= dt.id();
if(Objects.isNull(jndi.lookupByName("DYNAMIC_QUEUES_"+dt.getDestinationTransport()))){
defaultCamelContext = new DefaultCamelContext();
defaultCamelContext.setName("DYNAMIC_QUEUES_"+dt.getDestinationTransport());
//getting exception here, while trying to bind
jndi.bind("DYNAMIC_QUEUES_"+dt.getDestinationTransport(), defaultCamelContext);
}
else {
defaultCamelContext = (DefaultCamelContext) jndi.lookup("DYNAMIC_QUEUES_"+dt.getDestinationTransport());
}
context= defaultCamelContext;
context.getProperties().put(Exchange.LOG_DEBUG_BODY_STREAMS, "true");
context.addRoutes(new RouteBuilder() {
/**Code for creating route**/
}
context.start();
}
Log
ERROR [stderr] (Thread-89) java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only
01:26:57,536 ERROR [stderr] (Thread-89) at org.jboss.as.naming.WritableServiceBasedNamingStore.requireOwner(WritableServiceBasedNamingStore.java:161)
01:26:57,536 ERROR [stderr] (Thread-89) at org.jboss.as.naming.WritableServiceBasedNamingStore.bind(WritableServiceBasedNamingStore.java:66)
01:26:57,536 ERROR [stderr] (Thread-89) at org.jboss.as.naming.NamingContext.bind(NamingContext.java:253)
01:26:57,537 ERROR [stderr] (Thread-89) at org.jboss.as.naming.InitialContext$DefaultInitialContext.bind(InitialContext.java:260)
01:26:57,537 ERROR [stderr] (Thread-89) at org.jboss.as.naming.NamingContext.bind(NamingContext.java:262)
01:26:57,537 ERROR [stderr] (Thread-89) at javax.naming.InitialContext.bind(InitialContext.java:425)
01:26:57,537 ERROR [stderr] (Thread-89) at javax.naming.InitialContext.bind(InitialContext.java:425)
01:26:57,537 ERROR [stderr] (Thread-89) at org.apache.camel.impl.JndiRegistry.bind(JndiRegistry.java:124)
01:26:57,537 ERROR [stderr] (Thread-89) at com.sial.integration.routing.AsyncCamelDynamicFTPRoute.createRoute(AsyncCamelDynamicFTPRoute.java:91)
01:26:57,537 ERROR [stderr] (Thread-89) at com.sial.integration.routing.AsyncCamelDynamicFTPRoute$Proxy$_$$_WeldClientProxy.createRoute(Unknown Source)
01:26:57,537 ERROR [stderr] (Thread-89) at com.sial.integration.api.CallableExampleDT.call(CallableExampleDT.java:27)
01:26:57,537 ERROR [stderr] (Thread-89) at java.util.concurrent.FutureTask.run(FutureTask.java:266)
01:26:57,537 ERROR [stderr] (Thread-89) at java.lang.Thread.run(Thread.java:745)

java.lang.ClassNotFoundException: org.jpos.iso.ISOException

I'm beginner for using JPOS with ISO8583. At this time, I try my application using Spring to build the request using JPOS where I want to send it to BASE24.
Here my code for build :
public class BuildISO {
public void sentISOMsg(String hostname, int portNumber) {
// Create Packager based on XML that contain DE type
GenericPackager packager;
ASCIIChannel channel;
try {
packager = new GenericPackager("packager/iso93ascii.xml");
channel = new ASCIIChannel(hostname, portNumber, packager);
ISOMUX isoMux = new ISOMUX(channel) {
#Override
protected String getKey(ISOMsg m) throws ISOException {
return super.getKey(m);
}
};
new Thread(isoMux).start();
// Create ISO Message
ISOMsg isoRequest = new ISOMsg();
isoRequest.setMTI("1800");
isoRequest.set(3, "123456");
isoRequest.set(7, new SimpleDateFormat("yyyyMMdd").format(new Date()));
isoRequest.set(11, "000001");
isoRequest.set(12, new SimpleDateFormat("HHmmss").format(new Date()));
isoRequest.set(13, new SimpleDateFormat("MMdd").format(new Date()));
isoRequest.set(48, "Tutorial ISO 8583 Dengan Java");
isoRequest.set(70, "001");
ISORequest req = new ISORequest(isoRequest);
isoMux.queue(req);
ISOMsg isoReply = req.getResponse(50*1000);
if (isoReply != null) {
System.out.println("Req ["+new String(isoRequest.pack()) + "]");
System.out.println("Res ["+new String(isoReply.pack()) + "]");
}
// print the DE list
logISOMsg(isoRequest);
// Get and print the output result
byte[] data = isoRequest.pack();
System.out.println("RESULT : " + new String(data));
} catch (ISOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void logISOMsg(ISOMsg msg) {
System.out.println("----ISO MESSAGE-----");
try {
System.out.println(" MTI : " + msg.getMTI());
for (int i=1;i<=msg.getMaxField();i++) {
if (msg.hasField(i)) {
System.out.println(" Field-"+i+" : "+msg.getString(i));
}
}
} catch (ISOException e) {
e.printStackTrace();
} finally {
System.out.println("--------------------");
}
}
}
and next, while I want to call that class in here :
public #ResponseBody ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String hostname = request.getParameter("hostname");
int portNumber = Integer.parseInt(request.getParameter("portNumber"));
System.out.println("handleRequest... : " + hostname + " : " + portNumber);
BuildISO buildISO = new BuildISO();
buildISO.sentISOMsg(hostname, portNumber);
return null;
}
I got error like this :
SEVERE: Servlet.service() for servlet spring threw exception
java.lang.ClassNotFoundException: org.jpos.iso.ISOException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
at org.sprint.controller.HandleController.handleRequest(HandleController.java:28)
at org.sprint.controller.HandleController$$FastClassByCGLIB$$fc3d18c.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at org.sprint.controller.HandleController$$EnhancerByCGLIB$$fbdc3830.handleRequest(<generated>)
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:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:722)
I have searched through StackOverflow's already asked questions, but have not found any of the situations in which the changes to the project were NONE. So I am feeling quite frustrated now because I have actually changed NOTHING and my project has stopped working. Help me please, any ideas would be grateful.
You should be sure that you have all jars in the CLASSPATH. In your case it is jpos.jar. And they all (with Spring) should be loaded withing the same classloader.
And one more advice: add -verbose option to the java (I guess Tomcat) to see from where your classes are loaded.
Please add the maven jpos dependency to you project.
<dependency>
<groupId>org.jpos</groupId>
<artifactId>jpos</artifactId>
<version>1.9.4</version>
</dependency>
Choose any one of the repository available from maven Maven Repository Link

How to disable spring destruction callback on object returned from controller

EDIT: This turned out to be something else in my configuration
Whenever I return an object with an inferable destruction method from a rest controller, the returned object gets closed, is it possible to disable this?
For example if I have an object like this:
public class MyObject implements AutoCloseable {
// Some json
private #JsonValue String foo = "hello world";
public void close () throws Exception {
System.out.println ("close()");
new Throwable ("STACK TRACE").printStackTrace (System.out);
}
}
And a controller like this:
#Controller
public class MyController {
private Map<String, MyObject> objects = new HashMap<> ();
#PostConstruct
private void populate () {
objects.put ("one", new MyObject ());
objects.put ("two", new MyObject ());
}
#RequestMapping ("/hello/{id}")
#ResponseBody
public MyObject test (#PathVariable ("id") String id) {
return objects.get (id);
}
}
Spring will call MyObject.close() after it is returned from the controller method. This is clearly not a spring managed object and I'd like to disable closing it, syntactically at the controller method site, is that possible?
This is with Spring 3.2 and 4.0, from googling around I believe it doesn't happen in 3.1.
EDIT: Posting the stack trace, the final cleanup() method has a #PreDestroy annotation on it, but same thing happens if I implement AutoCloseable. Objects of SimpleDataset class are not managed by Spring.
java.lang.Throwable: STACK TRACE
at edu.dfci.cccb.mev.dataset.domain.simple.SimpleDataset.cleanup(SimpleDataset.java:106)
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:601)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeDestroyMethods(InitDestroyAnnotationBeanPostProcessor.java:314)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeDestruction(InitDestroyAnnotationBeanPostProcessor.java:153)
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:238)
at org.springframework.beans.factory.support.DisposableBeanAdapter.run(DisposableBeanAdapter.java:231)
at org.springframework.web.context.request.AbstractRequestAttributes.executeRequestDestructionCallbacks(AbstractRequestAttributes.java:91)
at org.springframework.web.context.request.AbstractRequestAttributes.requestCompleted(AbstractRequestAttributes.java:47)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:949)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:949)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1011)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:722)
When you have #ResponseBody annotated handler method, Spring uses a RequestResponseBodyMethodProcessor to handle the value returned.
This is done in ServletInvocableHandlerMethod#invokeAndHandler(..) which is implemented as such
public final void invokeAndHandle(ServletWebRequest webRequest,
ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
setResponseStatus(webRequest);
if (returnValue == null) {
if (isRequestNotModified(webRequest) || hasResponseStatus() || mavContainer.isRequestHandled()) {
mavContainer.setRequestHandled(true);
return;
}
}
else if (StringUtils.hasText(this.responseReason)) {
mavContainer.setRequestHandled(true);
return;
}
mavContainer.setRequestHandled(false);
try {
this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
}
catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);
}
throw ex;
}
}
where
this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
delegates to the RequestResponseBodyMethodProcessor. Nothing in here calls close() on your return value.
What you are describing is not possible by default. You must have something else in your configuration.

JAAS exception null username and password

I followed this tutorial to learn JAAS. That example worked for me, so I created my own version (I'm using Tomcat 6 and Java 6), but I can not get it to work (exception on the bottom of the post).
(I can't put online the sources in a ZIP because the proxy. Sorry.)
This is the JAAS:
TestJAAS {
test.auth.MyModule required debug=true;
};
This is the user Principal:
public class MyUser implements Principal {
private String name;
public MyUser(String name) {
super();
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
This is the role Principal:
public final class MyRole implements Principal {
public String getName() {
return "Superman";
}
}
This is the login module:
public class MyModule implements LoginModule {
private CallbackHandler handler;
private Subject subject;
private MyUser user;
private final MyRole ROLE = new MyRole();
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.handler = callbackHandler;
this.subject = subject;
}
public boolean login() throws LoginException {
NameCallback nc = new NameCallback("login");
PasswordCallback pc = new PasswordCallback("password", false);
String name = nc.getName();
String pass = String.valueOf(pc.getPassword());
try {
handler.handle(new Callback[]{nc, pc});
} catch (Exception ex) {
throw new LoginException(ex.getMessage());
}
if ("123".equals(name) && "secret".equals(pass)) {
user = new MyUser(name);
return true;
}
throw new LoginException();
}
public boolean commit() throws LoginException {
subject.getPrincipals().add(user);
subject.getPrincipals().add(ROLE);
return true;
}
public boolean abort() throws LoginException {
return false;
}
public boolean logout() throws LoginException {
subject.getPrincipals().remove(user);
subject.getPrincipals().remove(ROLE);
return true;
}
}
This is the context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Realm className="org.apache.catalina.realm.JAASRealm" appName="TestJAAS"
userClassNames="test.auth.MyUser" roleClassNames="test.auth.MyRole" />
</Context>
And this is the web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>MyProtectedResources</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Superman</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>Superman</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>MyProtectedResources</realm-name>
</login-config>
And this is the exception when I try to log in on http://localhost:8080/TestJAAS/admin/admin.html:
5-dic-2013 10.07.29 org.apache.catalina.realm.JAASRealm authenticate
AVVERTENZA: Login exception authenticating username "123"
javax.security.auth.login.LoginException: java.lang.NullPointerException
at java.lang.String.<init>(String.java:177)
at java.lang.String.valueOf(String.java:2840)
at test.auth.MyModule.login(MyModule.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:769)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
at javax.security.auth.login.LoginContext.login(LoginContext.java:579)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:409)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:334)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:181)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:872)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
at javax.security.auth.login.LoginContext.login(LoginContext.java:579)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:409)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:334)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:181)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
The config file is loaded correctly. Why my username and password are null? Thanks in advance.
You have at least one error, located in this code:
String name = nc.getName();
String pass = String.valueOf(pc.getPassword());
try {
handler.handle(new Callback[]{nc, pc});
} catch (Exception ex) {
throw new LoginException(ex.getMessage());
}
You read the name/password from the callbacks, before they are filled by the callback handler!!!
You will need to put the String name=...;String pass=... part after handler.handle(...). The example you linked does this too.

Jetty Websocket servlet InstantiationException problems

I'm having problems to make the websocket example of jetty work
public class App {
public static void main(String[] args) {
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(MyEchoServlet.class, "/test/*");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyEchoServlet extends WebSocketServlet {
#Override
public void configure(WebSocketServletFactory factory) {
//factory.getPolicy().setIdleTimeout(10000);
factory.register(MyEchoSocket.class);
}
}
#WebSocket(maxMessageSize = 64 * 1024)
public class MyEchoSocket {
Session session;
#OnWebSocketConnect
public void onConnect(Session session){
this.session = session;
System.out.println("init "+session.getUpgradeRequest().getRequestURI().getPath() );
}
#OnWebSocketMessage
public void onText(String msg) {
System.out.println("rec "+msg );
try {
session.getRemote().sendString(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("MyWebSocket.onClose()");
}
}
}
gives the following error as soon as I try to create a Websocket from javascript:
var ws = new WebSocket("ws://localhost:8080/test/");
server error:
2013-09-14 15:57:04.076 INFO Server - jetty-9.0.5.v20130815
2013-09-14 15:57:04.122 INFO ServerConnector - Started ServerConnector#1a51ce0{HTTP/1.1}{0.0.0.0:8080}
2013-09-14 15:57:11.700 WARN ContextHandler - unavailable
java.lang.InstantiationException: app.App$MyEchoServlet
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:979)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:523)
at org.eclipse.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:424)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:505)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:434)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Unknown Source)
2013-09-14 15:57:11.706 WARN ServletHandler -
javax.servlet.ServletException: app.App$MyEchoServlet-4598284#e19c6ca5==app.App$MyEchoServlet,-1,false
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:563)
at org.eclipse.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:424)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:505)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:434)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.InstantiationException: app.App$MyEchoServlet
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:979)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:523)
... 13 more
jetty version: 9.0.5v20130815 (from maven eclipse.jetty repo)
Since you have that declared both your servlet and socket as inner classes, change the following 2 lines of your code ...
// From
public class MyEchoServlet extends WebSocketServlet {
// To
public static class MyEchoServlet extends WebSocketServlet {
// From
public class MyEchoSocket {
// To
public static class MyEchoSocket {
This is because Java cannot just instantiate a non-static inner class.
Try this from your main() method and you'll see ...
Servlet test = new MyEchoServlet();

Categories