How can I make JNDI Registry thread safe? - java

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)

Related

Mapping the RabbitListenerExceptionHandler with the Micronaut Global ExceptionHandler

I am trying to handle the exception thrown from the Rabbit Listener and expose the error to the Rest endpoint.
Rabbit Listener
#Queue(ProductTopicConstants.GET_PRODUCT)
public ProductViewModel find(String id) {
try {
LOG.info(String.format("Listener --> Getting product for specified id = %s", id));
ProductSearchCriteria criteria = new ProductSearchCriteria();
criteria.setId(id);
Bson query = QueryBuilder.QueryBuilder(criteria, Bson.class).get(0);
ProductViewModel productViewModel = Single.fromPublisher(
repository.getCollection(ProductConstrants.PRODUCT_COLLECTION_NAME, Product.class)
.find(query)).map(successValue -> {
return new ProductViewModel(
successValue.getId().toString(),
successValue.getName(),
successValue.getDescription(),
successValue.getPrice()
);
}).blockingGet();
return productViewModel;
} catch (Exception ex) {
throw ex;
}
}
From the listener I have thrown an exception and it is handle in the RabbitListenerExceptionHandler as shown below
#Singleton
#Primary
#Replaces(DefaultRabbitListenerExceptionHandler.class)
public class RabbitListenerExceptionHandler implements io.micronaut.rabbitmq.exception.RabbitListenerExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(RabbitListenerExceptionHandler.class);
#Override
public void handle(RabbitListenerException exception) {
if (LOG.isErrorEnabled()) {
Optional<RabbitConsumerState> messageState = exception.getMessageState();
if (messageState.isPresent()) {
//LOG.error("Error processing a message for RabbitMQ consumer [" + exception.getListener() + "]", exception);
throw new GlobalException();
} else {
LOG.error("RabbitMQ consumer [" + exception.getListener() + "] produced an error", exception);
}
}
}
}
Now I have a Global exception handler where it handles HTTP Request and Response.
public class GlobalException extends RuntimeException{
}
#Produces
#Singleton
#Requires(classes = {GlobalException.class, ExceptionHandler.class})
public class GlobalExceptionHandler implements ExceptionHandler<GlobalException, HttpResponse> {
#Override
public HttpResponse handle(HttpRequest request, GlobalException exception) {
return HttpResponse.ok(0);
}
}
When I have throw new GlobalException(); from RabbitListenerExceptionHandler the exception is not watched in the GlobalExceptionHandler
I get an exception as
fete.bird.common.extension.GlobalException: null
at fete.bird.common.extension.RabbitListenerExceptionHandler.handle(RabbitListenerExceptionHandler.java:25)
at fete.bird.common.extension.RabbitListenerExceptionHandler.handle(RabbitListenerExceptionHandler.java:14)
at io.micronaut.rabbitmq.intercept.RabbitMQConsumerAdvice.handleException(RabbitMQConsumerAdvice.java:343)
at io.micronaut.rabbitmq.intercept.RabbitMQConsumerAdvice.access$600(RabbitMQConsumerAdvice.java:67)
at io.micronaut.rabbitmq.intercept.RabbitMQConsumerAdvice$1.doHandleDelivery(RabbitMQConsumerAdvice.java:255)
at io.micronaut.rabbitmq.intercept.RabbitMQConsumerAdvice$1.handleDelivery(RabbitMQConsumerAdvice.java:284)
at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:149)
at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:104)
at io.micronaut.scheduling.instrument.InvocationInstrumenterWrappedRunnable.run(InvocationInstrumenterWrappedRunnable.java:47)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
08:41:35.266 [RxComputationThreadPool-3] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: The source did not signal an event for 10000000000 nanoseconds and has been terminated.
java.util.concurrent.TimeoutException: The source did not signal an event for 10000000000 nanoseconds and has been terminated.
at io.reactivex.internal.operators.flowable.FlowableTimeoutTimed$TimeoutSubscriber.onTimeout(FlowableTimeoutTimed.java:139)
at io.reactivex.internal.operators.flowable.FlowableTimeoutTimed$TimeoutTask.run(FlowableTimeoutTimed.java:170)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
Exception handlers used for HTTP have no relationship to the ones used for handling messaging exceptions and they are not designed to be called as a result of exceptions thrown from listeners or listener exception handlers.

Why would my resultset be coming up as false?

I'm working on a project for my programming class and the teacher encourages to use stackoverflow for assistance. My problem is as follows: in my if with sResult.next() is coming back false. I'm trying to obtain one row from my derby database.
I have verified my productUuid is obtaining a UUID, preparedstatement is active. I have checked that my findAll for the query is working and it is.
The interceptor is supposed to return the class name that is being used.
My query:
private static final String QUERY_02 =
"SELECT oid, product_name, product_desc, product_price, product_sku, product_inv FROM PRODUCT WHERE oid=?";
My UUIDUtils:
public class UUIDUtils {
public static UUID asUuid(byte[] bytes) {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long firstLong = bb.getLong();
final long secondLong = bb.getLong();
return new UUID(firstLong, secondLong);
}
public static byte[] asBytes(UUID uuid) {
final ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
My singleProduct:
public ProductDTO singleProduct(UUID productUuid) throws MyStoreException {
log().trace("Entered singleProduct()");
ProductDTO sProduct = null;
try (final Connection connection = datasource.getConnection();
final PreparedStatement sPre = connection.prepareStatement(QUERY_02);) {
sPre.setBytes(1, UUIDUtils.asBytes(productUuid));
log().trace("PreparedStatment connection is active: {}", !sPre.isClosed());
log().trace("productUuid passed through ProductQueryImpl: {}" , productUuid);
ResultSet sResult = sPre.executeQuery();
if(sResult.next()) {
sProduct = new ProductDTO(productUuid,
sResult.getString("product_name"),
sResult.getString("product_desc"),
sResult.getDouble("product_price"),
sResult.getString("product_sku"),
sResult.getInt("product_inv"));
}else {
log().error("Product not found");
}
return sProduct;
}catch(final SQLException ex2) {
log().error(ex2.getMessage(), ex2);
throw new MyStoreException(ex2.getMessage());
}
}
My Console:
00:05:04,092 TRACE [ca.sait.mystore.mvc.model.ProductModel] (default task-1) Entered postConstruct()
00:05:04,094 TRACE [ca.sait.mystore.interceptors.LogInterceptors] (default task-1) Entered logInterceptor(context)
00:05:04,094 DEBUG [ca.sait.mystore.interceptors.LogInterceptors] (default task-1) Method Name: singleProduct
00:05:04,094 TRACE [ca.sait.mystore.dao.ProductQueryImpl] (default task-1) Entered singleProduct()
00:05:04,096 TRACE [ca.sait.mystore.dao.ProductQueryImpl] (default task-1) PreparedStatment connection is active: true
00:05:04,096 TRACE [ca.sait.mystore.dao.ProductQueryImpl] (default task-1) productUuid passed through ProductQueryImpl: 00b6d373-af18-54ed-f8c9-7f9d986a834a
00:05:04,097 ERROR [ca.sait.mystore.dao.ProductQueryImpl] (default task-1) Product not found
00:05:04,098 DEBUG [ca.sait.mystore.interceptors.LogInterceptors] (default task-1) Returning Null
00:05:04,098 TRACE [ca.sait.mystore.interceptors.LogInterceptors] (default task-1) Exited logInterceptor(context)
00:05:04,099 TRACE [ca.sait.mystore.mvc.model.ProductModel] (default task-1) Following UUID passed through Model: 00b6d373-af18-54ed-f8c9-7f9d986a834a
00:05:04,099 TRACE [ca.sait.mystore.mvc.model.ProductModel] (default task-1) Exited postConstruct()

Getting a MappingException due to a ClassCastException while saving an object using Morphia-MongoDB

I have a Java class which has the following structure.
class Item{
...
#Embedded("zpl")
public List<ZplList> zplList = new ArrayList<ZplList>();
#Embedded("rohs")
public List<RohsList> rohsList = new ArrayList<RohsList>();
...
//Getters and setters
}
My ZplList class looks like this.
#Embedded
public class ZplList {
#Property("csass")
#org.javers.core.metamodel.annotation.Id
public String zpl;
#Property("csasd")
public Date startDate;
#Property("csaed")
public Date endDate;
#Override
public boolean equals(Object object) {
ZplList obj = (ZplList) object;
if (this.zpl==null ? obj.zpl!=null : !this.zpl.equals(obj.zpl)) {
return false;
}
if (this.startDate==null ? obj.startDate!=null :
!this.startDate.equals(obj.startDate)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.zpl.hashCode();
if(this.startDate!=null)
hash = 7 * hash + this.startDate.hashCode();
return hash;
}
}
My RohsList class looks similar to ZplList class.
#Embedded
public class RohsList {
#Property("rohs")
public String rohs;
#Property("rhssd")
public Date startDate;
#Property("rhsed")
public Date endDate;
#Override
public boolean equals(Object object) {
RohsList obj = (RohsList) object;
if (this.rohs==null ? obj.rohs!=null : !this.rohs.equals(obj.rohs)) {
return false;
}
if (this.startDate==null ? obj.startDate!=null :
!this.startDate.equals(obj.startDate)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 3;
if(this.rohs!=null)
hash = 7 * hash + this.rohs.hashCode();
if(this.startDate!=null)
hash = 7 * hash + this.startDate.hashCode();
return hash;
}
}
When I try to save an Item object using Morphia, I am getting an exception as follows in the datastore.save() call. Is there any issue with my annotations? Please suggest a fix for this.
14:36:29,771 ERROR [stderr] (http--127.0.0.1-8080-3) org.mongodb.morphia.mapping.MappingException: Error mapping field:com.mdm.ui.web.domain.Item.rohsList
14:36:29,773 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:906)
14:36:29,774 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:535)
14:36:29,774 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.DatastoreImpl.entityToDBObj(DatastoreImpl.java:1322)
14:36:29,775 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:1219)
14:36:29,775 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:704)
14:36:29,776 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:698)
14:36:29,777 ERROR [stderr] (http--127.0.0.1-8080-3) at com.mdm.ui.logic.dao.impl.SingleItemDaoImpl.submitItem(SingleItemDaoImpl.java:1532)
14:36:29,797 ERROR [stderr] (http--127.0.0.1-8080-3) Caused by: java.lang.ClassCastException: com.mdm.ui.web.domain.ZplList cannot be cast to com.mdm.ui.web.domain.RohsList
14:36:29,797 ERROR [stderr] (http--127.0.0.1-8080-3) at com.mdm.ui.web.domain.RohsList.equals(RohsList.java:57)
14:36:29,798 ERROR [stderr] (http--127.0.0.1-8080-3) at java.util.HashMap.put(Unknown Source)
14:36:29,798 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:910)
14:36:29,798 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:535)
14:36:29,799 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.EmbeddedMapper.writeCollection(EmbeddedMapper.java:235)
14:36:29,811 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.EmbeddedMapper.toDBObject(EmbeddedMapper.java:88)
14:36:29,812 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.writeMappedField(Mapper.java:793)
14:36:29,813 ERROR [stderr] (http--127.0.0.1-8080-3) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:904)

How to override CXF AbstractInvoker?

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>

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