NullPointerException HttpOutput.write with jetty http/2 server - maven

I compile my jetty project with http/2 When i try to access it's returns this:
java.io.IOException: java.lang.NullPointerException
at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:229)
at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:496)
at org.springframework.util.StreamUtils.copy(StreamUtils.java:128)
at org.springframework.http.converter.ResourceHttpMessageConverter.writeContent(ResourceHttpMessageConverter.java:115)
at org.springframework.http.converter.ResourceHttpMessageConverter.writeInternal(ResourceHttpMessageConverter.java:107)
at org.springframework.http.converter.ResourceHttpMessageConverter.writeInternal(ResourceHttpMessageConverter.java:50)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:227)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:380)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at com.mamuso.rest.base.security.filters.SimpleCorsFilter.doFilter(SimpleCorsFilter.java:37)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:523)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:267)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745)
However if I generate the image with htttp1 it's working properly
Here is where i instantiate server:
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(500);
mServer = new Server(threadPool);
mServer.addBean(new ScheduledExecutorScheduler());
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(mAppConfig.getServerPort());
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()});
mServer.setHandler(handlers);
mServer.setDumpAfterStart(false);
mServer.setDumpBeforeStop(false);
mServer.setStopAtShutdown(true);
Here I Define that is type http2:
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(mAppConfig.getServerKeystorePath());
sslContextFactory.setKeyStorePassword(mAppConfig.getServerKeystorePassword());
sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);
sslContextFactory.setUseCipherSuitesOrder(true);
// IMPROVE: exclude all but used ones? do not hardcode?
sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
// SSL HTTP Configuration
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// HTTP/2 Connection Factory
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfig);
NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable();
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol("h2");
// SSL Connection Factory
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,
alpn.getProtocol());
// HTTP/2 Connector
ServerConnector http2Connector =
new ServerConnector(mServer,ssl, alpn, h2,
new HttpConnectionFactory(httpsConfig));
http2Connector.setPort(mAppConfig.getServerPort());
http2Connector.setIdleTimeout(IDLE_TIMEOUT);
mServer.addConnector(http2Connector);

Related

Setting a timeout on tcp client spring integration

I am trying to establish a connection between socket server, No Matter how much value I pass to timeout, It is timing out at 10 seconds, What is the correct way to set a time out, Thanks.
#Bean(name = "mastercardConnectionFactory")
public AbstractClientConnectionFactory clientConnectionFactoryMastercard() {
ISOConnectionProperties mastercard = applicationProperties.getIsoServers().getMastercard();
TcpNioClientConnectionFactory tcpNioClientConnectionFactory =
new TcpNioClientConnectionFactory(mastercard.getHost(), mastercard.getPort());
tcpNioClientConnectionFactory.setUsingDirectBuffers(true);
tcpNioClientConnectionFactory.setApplicationEventPublisher(applicationEventPublisher);
tcpNioClientConnectionFactory.setSoTimeout(20_000);
return new CachingClientConnectionFactory(tcpNioClientConnectionFactory, mastercard.getPoolSize());
}
#Bean
#ServiceActivator(inputChannel = "outboundChannelMastercard")
public MessageHandler outboundGatewayMc(
#Qualifier("mastercardConnectionFactory") AbstractClientConnectionFactory clientConnectionFactory) {
TcpOutboundGateway tcpOutboundGateway = new TcpOutboundGateway();
tcpOutboundGateway.setConnectionFactory(clientConnectionFactory);
tcpOutboundGateway.setRequestTimeout(20_000);
tcpOutboundGateway.setUnsolicitedMessageChannelName("unsolicited");
return tcpOutboundGateway;
}
StackTrace: Connection is available, I see subscribers
2022-08-02 17:40:55,989 [http-nio-8085-exec-5][8269d4eb-8c21-4256-a036-617b7b86a640] ERROR org.springframework.integration.ip.tcp.TcpOutboundGateway - Tcp Gateway exception
org.springframework.integration.MessageTimeoutException: Timed out waiting for response; component: outboundGatewayVisa
at org.springframework.integration.ip.tcp.TcpOutboundGateway.getReply(TcpOutboundGateway.java:293)
at org.springframework.integration.ip.tcp.TcpOutboundGateway.handleRequestMessage(TcpOutboundGateway.java:234)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:136)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:317)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:272)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.integration.router.AbstractMessageRouter.doSend(AbstractMessageRouter.java:213)
at org.springframework.integration.router.AbstractMessageRouter.handleMessageInternal(AbstractMessageRouter.java:195)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56)
at org.springframework.integration.handler.ReplyProducingMessageHandlerWrapper.handleRequestMessage(ReplyProducingMessageHandlerWrapper.java:59)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:136)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:317)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:272)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:233)
at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessagingTemplate.sendAndReceive(AbstractMessagingTemplate.java:46)
at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:97)
at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:38)
at org.springframework.messaging.core.AbstractMessagingTemplate.convertSendAndReceive(AbstractMessagingTemplate.java:96)
at org.springframework.messaging.core.AbstractMessagingTemplate.convertSendAndReceive(AbstractMessagingTemplate.java:86)
at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:514)
at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceive(MessagingGatewaySupport.java:487)
at org.springframework.integration.gateway.GatewayProxyFactoryBean.sendOrSendAndReceive(GatewayProxyFactoryBean.java:652)
at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:588)
at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:555)
at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:544)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy149.send(Unknown Source)
at
Use setRemoteTimeout.
requestTimeout is the timeout while waiting to get access to a shared connection.
Also, make sure the connection factory is configured with the correct deserializer; the default deserializer expects \r\n to delimit the response.

How do I figure out what object my session is trying to serialize?

I recently upgraded to Spring Security 4.2.3.RELEASE. I'm also using spymemcached v 2.8.4. I'm running into this situation where for some reason Spring is trying to serialize service implementation classes. I can't figure out where this is coming from. The line of my code that the exception refers to is
Set<Session> userSessions = (Set<Session>) memcachedClient.get(userId);
...
memcachedClient.set(userId, sessionTimeoutInSeconds.intValue(), userSessions); // dies here
with the mysterious error (the "java.io.NotSerializableException: org.mainco.subco.ecom.service.ContractServiceImpl" is buried within) ...
09:06:47,771 ERROR [io.undertow.request] (default task-58) UT005023: Exception handling request to /myproject/registration/save: java.lang.IllegalArgumentException: Non-serializable object
at net.spy.memcached.transcoders.BaseSerializingTranscoder.serialize(BaseSerializingTranscoder.java:110)
at net.spy.memcached.transcoders.SerializingTranscoder.encode(SerializingTranscoder.java:162)
at net.spy.memcached.MemcachedClient.asyncStore(MemcachedClient.java:282)
at net.spy.memcached.MemcachedClient.set(MemcachedClient.java:733)
at net.spy.memcached.MemcachedClient.set(MemcachedClient.java:126)
at org.mainco.subco.session.service.MemcachedSessionService.associateUser(MemcachedSessionService.java:365)
at org.mainco.subco.session.service.MemcachedSessionService.setSessionSecurityContext(MemcachedSessionService.java:288)
at org.mainco.subco.core.security.SubcoSecurityContextRepository.saveContext(subcoSecurityContextRepository.java:116)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:198)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:784)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.NotSerializableException: org.mainco.subco.ecom.service.ContractServiceImpl
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
How do I figure out the object memcache is trying to serialize and thus figure out how it is referencing a service class to serialize?
The point of this question is not how do I make my service class serializable but why is my session trying to serialize it in the first place.
Why don't you try to enumerate the sessions and the attributes and java-serialize them to a dummy output stream until one fails ? when it fails you print attribute name and value class.
I suppose session is org.apache.catalina.Session. In your code add:
for(Session x : userSessions) checkSerializable(x.getSession());
with checkSerializable:
private static void checkSerializable(HttpSession s) {
Enumeration e = s.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Object value = s.getAttribute(name);
try
{
ObjectOutputStream out=new ObjectOutputStream(new ByteArrayOutputStream());
out.writeObject(value);
}
catch(NotSerializableException ex)
{
ex.printStackTrace();
System.out.println(name + " is not serializable, class is: " + value.getClass().getName());
}
catch(IOException e2)
{
throw new RuntimeException("Unexpected", e2);
}
}
}
I'm running into this situation where for some reason Spring is trying to serialize service implementation classes.
spring don't try to serialize implementation .
looks lite when you do
memcachedClient.set(userId, sessionTimeoutInSeconds.intValue(), userSessions);
it's expect for Serializable object ,but userSessions is not.
Set is not serializable , and type that you get
(Set) memcachedClient.get(userId);
is not serialized to. check if you can cast memcachedClient.get(userId) to something that is Serializable like HashSets or TreeSet ....
the worst it's you can try BUT you might get CastException
memcachedClient.set(userId, sessionTimeoutInSeconds.intValue(), (Serializable)userSessions);
you can iterate set and do simple check :
int count=0;
for(Session session: userSessions ){
log....
boolean isSerializable = checkIfSerializable(session);
count=isSerializable ? count+1 : count;
log
}
private static boolean checkIfSerializable(Object value) throws IllegalAccessException {
try {
ByteArrayOutputStream bf = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bf);
oos.writeObject(value);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bf.toByteArray()));
Object o = ois.readObject();
return true;
} catch (Exception e) {
System.out.println("----->>>> Not exactly Serializable : " + value);
}
return false;
}
So what about org.mainco.subco.ecom.service.ContractServiceImpl? Is this a spring bean?
I guess it has scope="session" and so it's bound to your session as one of it's attributes. And if you want to serialize your session - all of it's attributes has to be serializable.

Tibco SSL communication says no trusted certificates are set

I am trying to establish a SSL communication with Tibco EMS. TCP communication is successful and I was able to publish a message. I ma configuring it with JMS template. Below are the properties I have for communicating with Tibco.
#Tibco EMS Setup
tibco.ems.namingUrl=ssl://machineName:7223
##Tibco User name/pwd
java.naming.security.principal=testUser
java.naming.security.credentials=testUser
##Tibco Configuration details SSLQueueConnectionFactory
ems.connectionFactory=SSLQueueConnectionFactory
ems.queueName=queueName
ems.contextFactory=com.tibco.tibjms.naming.TibjmsInitialContextFactory
here is the code fro JMS template setup done in Spring.
public class JMSConfiguration {
#Autowired
private Environment environment;
#Bean
public JndiTemplate jndiTemplate() throws JMSException {
JndiTemplate jndiTemplate = new JndiTemplate();
Properties jndiProps = new Properties();
Properties props = System.getProperties();
jndiProps.setProperty("java.naming.security.principal", environment.getProperty("java.naming.security.principal"));
jndiProps.setProperty("java.naming.security.credentials", environment.getProperty("java.naming.security.credentials"));
jndiProps.setProperty("java.naming.factory.initial", environment.getProperty("ems.contextFactory"));
jndiProps.setProperty("java.naming.provider.url", environment.getProperty("tibco.ems.namingUrl"));
jndiProps.setProperty("com.tibco.tibjms.naming.security_protocol", "ssl");
jndiProps.setProperty("com.tibco.tibjms.naming.ssl_enable_verify_host", "false");
jndiTemplate.setEnvironment(jndiProps);
return jndiTemplate;
}
#Bean
public UserCredentialsConnectionFactoryAdapter authenticate() throws JMSException, NamingException {
UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
userCredentialsConnectionFactoryAdapter.setUsername(environment.getProperty("java.naming.security.principal"));
userCredentialsConnectionFactoryAdapter.setPassword(environment.getProperty("java.naming.security.credentials"));
userCredentialsConnectionFactoryAdapter.setTargetConnectionFactory(connectionFactoryProxy());
return userCredentialsConnectionFactoryAdapter;
}
#Bean
public JndiObjectFactoryBean jmsConnectionFactory() throws JMSException {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiTemplate(jndiTemplate());
jndiObjectFactoryBean.setJndiName(environment.getProperty("ems.connectionFactory"));
return jndiObjectFactoryBean;
}
#Bean
public JndiObjectFactoryBean jmsQueueName() throws JMSException {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiTemplate(jndiTemplate());
jndiObjectFactoryBean.setJndiName(environment.getProperty("ems.queueName"));
return jndiObjectFactoryBean;
}
#Bean
public TransactionAwareConnectionFactoryProxy connectionFactoryProxy() throws NamingException, JMSException {
return new TransactionAwareConnectionFactoryProxy((ConnectionFactory) jmsConnectionFactory().getObject());
}
#Bean(name="jmsTemplate")
public JmsTemplate jmsTemplate() throws JMSException, NamingException {
JmsTemplate jmsTemplate = new JmsTemplate(authenticate());
jmsTemplate.setSessionTransacted(false);
jmsTemplate.setReceiveTimeout(5000);
jmsTemplate.setDefaultDestination((Destination) jmsQueueName().getObject());
return jmsTemplate;
}
#Bean
public QueueMessageSender queueMessageSender() {
return new QueueMessageSender();
}
I have read this link and checked if the keys are present in server machine which is have .pem key and certificate in paths specified.
ssl_server_identity = machineName.crt.pem
ssl_server_key = machineName.key.pem
Here is the error I am getting when trying to publish an EMs message.
org.springframework.jms.JmsSecurityException: Can not initialize SSL client: no trusted certificates are set; nested exception is javax.jms.JMSSecurityException: Can not initialize SSL client: no trusted certificates are set
at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:291)
at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:169)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:496)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:568)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:559)
at com.project.name.jms.QueueMessageSender.postMessage(QueueMessageSender.java:32)
at com.project.name.controller.ControllerClass.publishEMS(ControllerClass.java:228)
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:497)
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:751)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused by: javax.jms.JMSSecurityException: Can not initialize SSL client: no trusted certificates are set
at com.tibco.tibjms.TibjmsxLinkSSL._initSSL(TibjmsxLinkSSL.java:281)
at com.tibco.tibjms.TibjmsxLinkSSL.connect(TibjmsxLinkSSL.java:383)
at com.tibco.tibjms.TibjmsConnection._create(TibjmsConnection.java:1354)
at com.tibco.tibjms.TibjmsConnection.<init>(TibjmsConnection.java:4320)
at com.tibco.tibjms.TibjmsQueueConnection.<init>(TibjmsQueueConnection.java:39)
at com.tibco.tibjms.TibjmsxCFImpl._createImpl(TibjmsxCFImpl.java:200)
at com.tibco.tibjms.TibjmsxCFImpl._createConnection(TibjmsxCFImpl.java:253)
at com.tibco.tibjms.TibjmsConnectionFactory.createConnection(TibjmsConnectionFactory.java:61)
at org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy.createConnection(TransactionAwareConnectionFactoryProxy.java:147)
at org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter.doCreateConnection(UserCredentialsConnectionFactoryAdapter.java:178)
at org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter.createConnection(UserCredentialsConnectionFactoryAdapter.java:152)
at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:180)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:483)
Weblogic is the server. Should I set anything in weblogic for SSL communication?
Please suggest if I need to add additional parameters in weblogic server to establish a communication. Also, here are the tibco dependencies I'm using in POM.
<dependency>
<groupId>com.tibco</groupId>
<artifactId>tibjms</artifactId>
<version>8.1.0</version>
</dependency>
<dependency>
<groupId>tibco</groupId>
<artifactId>tibcrypt</artifactId>
<version>2.14.100</version>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>javax.jms-api</artifactId>
<version>2.0</version>
<scope>compile</scope>
</dependency>
By default, WebLogic has only demo certs available. If you need to enable SSL communication for a WebLogic server, this and this are good places to start. You're going to have to add your certs to a JKS keystore file and point your WebLogic server at that file. Otherwise, WebLogic is only going to be presenting it's demo certificate to Tibco.

Spring Boot + Multipart file upload yields a Badly formatted multipart request

I am currently running with Spring Boot v1.3.0.BUILD-SNAPSHOT, and Spring v4.2.2.BUILD-SNAPSHOT.
If I attempt to perform a multi-file upload (via angular):
myService.upload = function(name ,content) {
var fd = new FormData();
fd.append('name', name);
fd.append('file', content);
return $http({
method: 'POST',
url: SERVER_BASE_URL + 'upload',
data: fd,
transformRequest: angular.identity,
headers: {
'Content-Type': 'multipart/form-data'
}}).then(function(res) {
return res.headers('Location');
}, function(reason) {
throw reason;
});
};
I get the error:
[WARN] org.eclipse.jetty.server.Request -
java.io.IOException: Missing initial multi part boundary
at org.eclipse.jetty.util.MultiPartInputStreamParser.parse(MultiPartInputStreamParser.java:507) ~[jetty-util-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.util.MultiPartInputStreamParser.getParts(MultiPartInputStreamParser.java:400) ~[jetty-util-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Request.getParts(Request.java:2139) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Request.extractMultipartParameters(Request.java:385) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Request.extractContentParameters(Request.java:308) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Request.extractParameters(Request.java:256) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Request.getParameter(Request.java:825) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:70) [spring-web-4.2.2.BUILD-SNAPSHOT.jar:4.2.2.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.2.BUILD-SNAPSHOT.jar:4.2.2.BUILD-SNAPSHOT]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) [jetty-servlet-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) [spring-web-4.2.2.BUILD-SNAPSHOT.jar:4.2.2.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.2.BUILD-SNAPSHOT.jar:4.2.2.BUILD-SNAPSHOT]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) [jetty-servlet-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.ja [jetty-servlet-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577) [jetty-security-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) [jetty-servlet-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.Server.handle(Server.java:499) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) [jetty-server-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) [jetty-io-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) [jetty-util-9.2.13.v20150730.jar:9.2.13.v20150730]
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) [jetty-util-9.2.13.v20150730.jar:9.2.13.30]1507
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
I have added A multipart resolver bean:
#Bean
public FilterRegistrationBean openEntityManagerFilterRegistrationBean() {
// Set upload filter
final MultipartFilter multipartFilter = new MultipartFilter();
final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(multipartFilter);
filterRegistrationBean.addInitParameter("multipartResolverBeanName", "commonsMultipartResolver");
return filterRegistrationBean;
}
#Bean
public CommonsMultipartResolver commonsMultipartResolver() {
final CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSize(-1);
return commonsMultipartResolver;
}
However it appears that hiddenHttpMethodFilter is still getting called before my multipart resolver:
[DEBUG] org.eclipse.jetty.servlet.ServletHandler - call filter characterEncodingFilter
[DEBUG] org.eclipse.jetty.servlet.ServletHandler - call filter hiddenHttpMethodFilter
[WARN] org.eclipse.jetty.util.MultiPartInputStreamParser - Badly formatted multipart request
I tried adding #Order(0) to my Bean, but that had no effect.
What else am I missing?
I do not use filter to upload files.
Try this approach here:
// in configs
  #Bean
     Public MultipartConfigElement multipartConfigElement () {
         End MultipartConfigFactory factory = new MultipartConfigFactory ();
         Factory.setMaxFileSize ( "50MB");
         Factory.setMaxRequestSize ( "50MB");
         Return factory.createMultipartConfig ();
     }
and
// in controller
#RequestMapping (value = "/ sendfile", method = RequestMethod.POST)
     Public ModelAndView formSubmit (#RequestParam ( "file") MultipartFile file) {
}
Note: remember to remove the filters that you put in the configs
I hope to help
Well this simply means there is issue with your angular js code.
You will have to debug on browser, what exactly is being sent, and definately it is missing headers. Use tools like firebug. Try this code.
var fd = new FormData();
fd.append('file', file);
fd.append('data', 'string');
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Absolutely essential are the following two properties of the config object:
transformRequest: angular.identity
overrides Angular's default serialization, leaving our data intact.
headers: {'Content-Type': undefined }
lets the browser detect the correct Content-Type as multipart/form-data, and fill in the correct boundary.

Ribbon with Spring Cloud and Eureka: java.lang.IllegalStateException: No instances available for Samarths-MacBook-Pro.local

I am working on Spring Boot Eureka Client Application with Ribbon Load Balancer.
I have two instances of the server registered with Eureka with the name "TEST". On the client side, I have the following code to fetch the server from Eureka.
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableEurekaClient
#RestController
public class EurekaConsumerApplication {
#Autowired
DiscoveryClient discoveryClient;
#Autowired
RestTemplate restTemplate;
#RequestMapping(value = "/",method = RequestMethod.GET)
String consumer(){
InstanceInfo instance = discoveryClient.getNextServerFromEureka("TEST", false);
URI uri = UriComponentsBuilder.fromUriString(instance.getHomePageUrl() + "baseDir")
.build()
.toUri();
String baseDir = restTemplate.getForObject(uri, String.class);
return baseDir;
}
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class, args);
}
}
application.yml
spring:
application:
name: consumer
info:
component: Consumer to fetch configuration
server:
port: 8090
eureka:
instance:
leaseRenewalIntervalInSeconds: 3
metadataMap:
instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${random.value}}}
client:
# Default values comes from org.springframework.cloud.netflix.eurek.EurekaClientConfigBean
region: default
registryFetchIntervalSeconds: 5
instanceInfoReplicationIntervalSeconds: 5
initialInstanceInfoReplicationIntervalSeconds: 5
serviceUrl:
defaultZone: http://localhost:8761/eureka/
availabilityZones:
default: ${APPLICATION_DOMAIN:${DOMAIN:defaultZone}}
However, when I hit the restful endpoint by using the following command, it gives an error:
curl http://localhost:8090/
This is the error:
{"exception":"java.lang.IllegalStateException","message":"org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No instances available for Samarths-MacBook-Pro.local","path":"/"}
Stacktrace:
2015-07-22 14:37:35.005 INFO 13841 --- [tp1334391583-19] c.netflix.loadbalancer.BaseLoadBalancer : Client:Samarths-MacBook-Pro.local instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=Samarths-MacBook-Pro.local,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2015-07-22 14:37:35.009 INFO 13841 --- [tp1334391583-19] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client Samarths-MacBook-Pro.local initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=Samarths-MacBook-Pro.local,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList#681eda37
2015-07-22 14:37:35.029 WARN 13841 --- [tp1334391583-19] o.eclipse.jetty.servlet.ServletHandler :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No instances available for Samarths-MacBook-Pro.local
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:295)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty..ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:68)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: No instances available for Samarths-MacBook-Pro.local
at org.springframework.cloud.netflix.ribbon.RibbonClientHttpRequestFactory.createRequest(RibbonClientHttpRequestFactory.java:64)
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:76)
at org.springframework.web.client.Rlate.doExecute(RestTemplate.java:565)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:253)
at com.securityscorecard.eureka.consumer.EurekaConsumerApplication.consumer(EurekaConsumerApplication.java:53)
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:497)
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)
... 38 common frames omitted
Looks like my server list is empty.
The RestTemplate you autowired is already connected to Ribbon. So you do a lookup by hand and then RestTemplate is trying to lookup the hostname passed in to ribbon. You have two options: 1) Don't use the netflix DiscoveryClient and pass the serviceId as a logical hostname to ribbon (http://TEST/myservice), 2) Don't use the autowired RestTemplate, create a new one for your class. My choice would be #1.
I got this working. The only change I had to make was in the way I was using RestTemplate api.
Error Code:
#Autowired
RestTemplate restTemplate;
#RequestMapping(value = "/",method = RequestMethod.GET)
String consumer(){
String baseDir = restTemplate.getForObject("TEST", String.class);
return baseDir;
}
Working Code:
#Autowired
RestTemplate restTemplate;
#RequestMapping(value = "/",method = RequestMethod.GET)
String consumer(){
String baseDir = restTemplate.getForObject("http://TEST", String.class);
return baseDir;
}
Solution:
The first parameter to restTemplate.getForObject should have the format of a URL. And the domain name should be the name of the service you want to discover.
Ex: http://TEST. Here, TEST is the name of my server registered to eureka registry
The question is already answered, but I found a workaround that seems neat and fixed our problem.
First declare a new #Component class and in it create a method that returns RestTemplate:
#Component
public class RestTemplateComponentFix{
#Autowired
SomeConfigurationYouNeed someConfiguration;
#LoadBalanced
public RestTemplate getRestTemplate() {
// TODO set up your restTemplate
rt.setRequestFactory( new HttpComponentsClientHttpRequestFactory() );
return rt;
}
}
After that just Autowire the restTemplateComponentFix in your class and when when you need the rest template call the restTemplate() method. Something like this:
#Service
public class someClass{
#Autowired
RestTemplateComponentFix restTemplateComponentFix;
public void methodUsingRestTemplate(){
// Some code...
RestTemplate rt = restTemplateComponentFix.getRestTemplate();
// Some code...
}
}
After that you can unit test with something like:
RestTemplate rt = Mockito.mock(RestTemplate.class)
when(restTemplateComponentFix.getRestTemplate()).thenReturn(rt);
when(rt.someMethod()).thenReturn(something);
Removing #LoadBalanced Annotation from RestTemplate works for me.
P.S: #LoadAnnotation is supposed to be applied only to Eureka Server which is your discovery server.
The question is already answered by #spencergibb, after trying #spencergibb way if you are still struggling with no instance avialable for ..MS... make sure that in pom.xml if you are using Netflix Eureka then avoid adding dependency for Netflix ribbon as Eureka itself internally uses ribbon.
This was causing problems for me.
RestTemplateBuilder works for me. As below-
#Service
public class someClass{
#Autowired
RestTemplateBuilder restTemplateBuilder;
public void methodUsingRestTemplate(){
restTemplateBuilder.build().getForObject("http://TEST", String.class);
}
}
Can be due to outdated release used in dependencies.
I was using a project from GitHub blog to understand the working of Microservices registry and discovery.
The dependency of netflix in that project was outdated,
spring-cloud-starter-netflix-eureka-server', version: '2.0.1.RELEASE'
After removing version, issue was solved as latest version would be used.

Resources