'java.security.cert.CertificateExpiredException: NotAfter' upon connecting secure web socket - java

I am trying to connect to a secured web socket to consume a API. Below is the source code. Hosting environment configuration is JRE 1.7 and Tomcat 7.
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.apache.log4j.Logger;
#ClientEndpoint
public final class SocketRateFeed
{
private static final Logger logger = Logger.getLogger(SocketRateFeed.class);
private Session sessionWS;
public static void startContainer()
{
try
{
URI wsURI = new URI("wss://websocket.abc.xyz/?api_key=qwerty&user_id=ASDF");
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(new SocketRateFeed() , wsURI);
}
catch(Exception exp)
{
logger.error(exp.getMessage() , exp);
}
}
....other annotated methods
}
This is stack trace.
28-02-2017 11:24:37 localhost-startStop-1 ERROR SocketRateFeed.startContainer(30) : The HTTP request to initiate the WebSocket connection failed
javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:325)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:166)
............
Caused by: java.util.concurrent.ExecutionException: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at org.apache.tomcat.websocket.AsyncChannelWrapperSecure$WrapperFuture.get(AsyncChannelWrapperSecure.java:511)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:291)
... 17 more
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1395)
at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:516)
at sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1193)
at sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1165)
at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:469)
at org.apache.tomcat.websocket.AsyncChannelWrapperSecure$WebSocketSslHandshakeThread.run(AsyncChannelWrapperSecure.java:371)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1702)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:281)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1477)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:213)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:961)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:901)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:899)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1333)
at org.apache.tomcat.websocket.AsyncChannelWrapperSecure$WebSocketSslHandshakeThread.run(AsyncChannelWrapperSecure.java:397)
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:350)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:260)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:283)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:138)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1464)
... 7 more
Caused by: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:159)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:353)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:191)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:279)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:345)
... 13 more
Caused by: java.security.cert.CertificateExpiredException: NotAfter: Sat May 21 17:56:00 IST 2016
at sun.security.x509.CertificateValidity.valid(CertificateValidity.java:273)
at sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:576)
at sun.security.provider.certpath.BasicChecker.verifyTimestamp(BasicChecker.java:184)
at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:136)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:133)
... 17 more
I would be very helpful if anyone can provide solution/workaround or bypass trick for this issue.
Thanks.

Related

Jersey Client Error - Unable to Parse Invalid Content-Type Header (need workaround)

I'm using Jersey Client 2.29 I believe.
When handling a request the server responds with Content-Type = application/ (of course that is a bogus value it is supposed to be application/json). jersey blows up because it can't parse the subtype of the media type:
java.util.concurrent.CompletionException: org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "application/"
at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:314)
at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:319)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1702)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "application/"
at org.glassfish.jersey.message.internal.InboundMessageContext.exception(InboundMessageContext.java:314)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:309)
at org.glassfish.jersey.message.internal.InboundMessageContext.getMediaType(InboundMessageContext.java:422)
at com.test.web.ext.filter.LoggingFilter.filter(LoggingFilter.java:94)
at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:109)
at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:97)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:147)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:259)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:743)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.process(Errors.java:205)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:741)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:432)
at org.glassfish.jersey.client.JerseyCompletionStageRxInvoker.lambda$method$1(JerseyCompletionStageRxInvoker.java:46)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
... 3 more
Caused by: javax.ws.rs.ProcessingException: java.lang.IllegalArgumentException: Error parsing media type 'application/'
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:428)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:422)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:307)
... 18 more
Caused by: java.lang.IllegalArgumentException: Error parsing media type 'application/'
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:69)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:37)
at javax.ws.rs.core.MediaType.valueOf(MediaType.java:196)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:426)
... 20 more
Caused by: java.text.ParseException: End of header.
at org.glassfish.jersey.message.internal.HttpHeaderReaderImpl.getNextCharacter(HttpHeaderReaderImpl.java:155)
at org.glassfish.jersey.message.internal.HttpHeaderReaderImpl.next(HttpHeaderReaderImpl.java:116)
at org.glassfish.jersey.message.internal.HttpHeaderReaderImpl.next(HttpHeaderReaderImpl.java:111)
at org.glassfish.jersey.message.internal.HttpHeaderReader.nextToken(HttpHeaderReader.java:104)
at org.glassfish.jersey.message.internal.MediaTypeProvider.valueOf(MediaTypeProvider.java:90)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:67)
... 23 more
github-MediaTypeProvider
I have no control of this 3rd party server and I have to be able to process this request.
Is there anyway around this?
Some property, setting, registering a custom media type provider, anything?
P.S.
I have successfully used ByteBuddy to redefine this method at runtime and handle the error with some extra special sauce but that is a major hack... I'd love a better option if it exists.
Client Configuration
final Client client = ClientBuilder.newBuilder()
.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED)
.property(ClientProperties.FOLLOW_REDIRECTS, false)
.sslContext(tls)
.hostnameVerifier(new NoOpHostnameVerifier())
.register(new CookiePersistFilter(NARRATIVE)) // #Priority(HEADER_DECORATOR)
.register(new LoggingFilter(NARRATIVE)) // #Priority(USER)
.register(MyFilter.class) // #Priority(50000)
.register(JsonReader.class)
.register(JsonWriter.class)
.register(HTMLReader.class)
.register(MultiPartFeature.class)
.build();
Filters are executed in this order:
MyFilter
LoggingFilter
CookiePersistFilter
As Paul Samsotha pointed out, I can fix this with a ClientResponseFilter using high priority. Here is one way one could do it.
import javax.annotation.Priority;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import com.selinc.winchester.common.narrative.INarrative;
import com.selinc.winchester.sentinel.Sentinel;
import com.selinc.winchester.wrestler.ResponsePriorities;
#Provider
#Priority(25000) // Note the priority ordering is reverse of ClientRequestFilter
public final class ResponseHeaderWorkaroundFilter implements ClientResponseFilter
{
#Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
{
try
{
// Attempt to read the Content-Type header.
responseContext.getMediaType();
}
catch (Throwable error)
{
// On error, set the Content-Type header to some default value.
responseContext.getHeaders()
.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
}
}
}

How to connect to LDAPS using Apache LDAP Client?

I'm following the user guides for Apache's LDAP Client API to connect to the ApacheDS LDAPS server. But it will not connect. I have tried everything. I'm able to connect to the LDAP server. The user guide isn't really helpful because they leave out some functions that are used in the examples. I'm using a generated certificate by ApacheDS.
import static org.junit.Assert.assertTrue;
import org.apache.directory.api.util.Network;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.NoVerificationTrustManager;
public class SecureP2P {
public static void main(String[] args) throws Exception {
LdapConnectionConfig sslConfig = new LdapConnectionConfig();
sslConfig.setLdapHost(Network.LOOPBACK_HOSTNAME);
sslConfig.setUseSsl(true);
sslConfig.setLdapPort(10636);
sslConfig.setSslProtocol("SSLv3");
sslConfig.setTrustManagers(new NoVerificationTrustManager());
try (LdapConnection connection = new LdapNetworkConnection(sslConfig)) {
connection.bind("uid=admin,ou=system", "secret");
assertTrue(((LdapNetworkConnection) connection).getConfig().isUseSsl());
assertTrue(connection.isAuthenticated());
}
}
}
Here is the error in the log files of the ApacheDS Server:
WARN [org.apache.mina.util.DefaultExceptionMonitor] - Unexpected exception.
org.apache.mina.core.filterchain.IoFilterLifeCycleException: onPreAdd(): sslFilter:SslFilter in (0x00000007: nio socket, server, /192.168.1.249:65465 => /192.168.1.249:10636)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:383)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.addLast(DefaultIoFilterChain.java:189)
at org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder.buildFilterChain(DefaultIoFilterChainBuilder.java:496)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.addNow(AbstractPollingIoProcessor.java:504)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.handleNewSessions(AbstractPollingIoProcessor.java:479)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:68)
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1088)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
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: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at sun.security.ssl.Handshaker.activate(Handshaker.java:503)
at sun.security.ssl.SSLEngineImpl.kickstartHandshake(SSLEngineImpl.java:729)
at sun.security.ssl.SSLEngineImpl.beginHandshake(SSLEngineImpl.java:756)
at org.apache.mina.filter.ssl.SslHandler.init(SslHandler.java:185)
at org.apache.mina.filter.ssl.SslFilter.onPreAdd(SslFilter.java:438)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:381)
... 10 more
Error message when running the client:
Exception in thread "main" org.apache.directory.ldap.client.api.exception.InvalidConnectionException: An established connection was aborted by the software in your host machine
at org.apache.directory.ldap.client.api.LdapNetworkConnection.writeRequest(LdapNetworkConnection.java:4190)
at org.apache.directory.ldap.client.api.LdapNetworkConnection.bindAsync(LdapNetworkConnection.java:1314)
at org.apache.directory.ldap.client.api.LdapNetworkConnection.bind(LdapNetworkConnection.java:1212)
at org.apache.directory.ldap.client.api.AbstractLdapConnection.bind(AbstractLdapConnection.java:127)
at org.apache.directory.ldap.client.api.AbstractLdapConnection.bind(AbstractLdapConnection.java:112)
at edu.fau.SecureP2P.main(SecureP2P.java:22)

Gemfire JDBC connection exception

I start the Gemfire server and bind him to the following address: myserver:10344. (Server and locator are started without problems) After that I check connection by the GFSH and client "pulse". All checks are successful. At the next step I develop my Java client and can't make a connection to the server.
My project is built by Maven with the following dependencies:
<dependency>
<groupId>com.pivotal.gemfirexd</groupId>
<artifactId>gemfirexd</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>com.pivotal.gemfirexd</groupId>
<artifactId>gemfirexd-client</artifactId>
<version>1.4.1</version>
</dependency>
(All Gemfire dependencies are downloaded from http://dist.gemstone.com/maven/release)
Code source:
package com.mycompany.app;
import java.sql.Connection;
import java.sql.DriverManager;
public class App {
private void connect() {
try {
Class.forName("com.pivotal.gemfirexd.jdbc.ClientDriver");
String x = "jdbc:gemfirexd://myserver:10344/";
System.out.println(x);
final Connection conn = DriverManager.getConnection(x);
System.out.println("Connected ");
conn.close();
System.out.println("Disconnected");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main( String[] args ) {
new App().connect();
}
}
I get the following exception:
java.sql.SQLNonTransientConnectionException: A communications error has been detected: Failed after trying all available servers: [], for control URL: myserver[10334].
at com.pivotal.gemfirexd.internal.client.am.SQLExceptionFactory40.getSQLException(SQLExceptionFactory40.java:77)
at com.pivotal.gemfirexd.internal.client.am.SqlException.getSQLException(SqlException.java:401)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.getPreferredServer(NetConnection.java:1554)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.preConnect(NetConnection.java:1902)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.newAgent_(NetConnection.java:2368)
at com.pivotal.gemfirexd.internal.client.am.Connection.<init>(Connection.java:595)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.<init>(NetConnection.java:248)
at com.pivotal.gemfirexd.internal.client.net.NetConnection40.<init>(NetConnection40.java:86)
at com.pivotal.gemfirexd.internal.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(ClientJDBCObjectFactoryImpl40.java:290)
at com.pivotal.gemfirexd.jdbc.ClientDriver.connect(ClientDriver.java:161)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.mycompany.app.App.connect(App.java:15)
at com.mycompany.app.App.main(App.java:27)
Caused by: DisconnectException 08006: A communications error has been detected: Failed after trying all available servers: [], for control URL: myserver[10334].
... 12 more
Caused by: java.sql.SQLNonTransientConnectionException: A communications error has been detected: Connection reset.
at com.pivotal.gemfirexd.internal.client.am.SQLExceptionFactory40.getSQLException(SQLExceptionFactory40.java:77)
at com.pivotal.gemfirexd.internal.client.am.SqlException.getSQLException(SqlException.java:401)
at com.pivotal.gemfirexd.jdbc.ClientDriver.connect(ClientDriver.java:170)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.getPreferredServer(NetConnection.java:1451)
... 11 more
Caused by: DisconnectException 08006: A communications error has been detected: Connection reset.
at com.pivotal.gemfirexd.internal.client.net.NetAgent.throwCommunicationsFailure(NetAgent.java:527)
at com.pivotal.gemfirexd.internal.client.net.Reply.fill(Reply.java:183)
at com.pivotal.gemfirexd.internal.client.net.Reply.ensureALayerDataInBuffer(Reply.java:222)
at com.pivotal.gemfirexd.internal.client.net.Reply.readDssHeader(Reply.java:324)
at com.pivotal.gemfirexd.internal.client.net.Reply.startSameIdChainParse(Reply.java:1154)
at com.pivotal.gemfirexd.internal.client.net.NetConnectionReply.readExchangeServerAttributes(NetConnectionReply.java:61)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.readServerAttributesAndKeyExchange(NetConnection.java:1013)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.flowServerAttributesAndKeyExchange(NetConnection.java:941)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.flowUSRIDONLconnect(NetConnection.java:796)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.flowConnect(NetConnection.java:580)
at com.pivotal.gemfirexd.internal.client.net.NetConnection.<init>(NetConnection.java:259)
at com.pivotal.gemfirexd.internal.client.net.NetConnection40.<init>(NetConnection40.java:86)
at com.pivotal.gemfirexd.internal.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(ClientJDBCObjectFactoryImpl40.java:290)
at com.pivotal.gemfirexd.jdbc.ClientDriver.connect(ClientDriver.java:161)
... 14 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at com.pivotal.gemfirexd.internal.client.net.Reply.fill(Reply.java:181)
... 26 more
I see that this is an old post but just in case you still want to know ....
The port you're specifying in your jdbc url is referring to the peer-membership discovery port, not the client-port (default 1527).
When you started the locator, there should've been info on the client port number as such (if you don't specify, default is 1527)
...
Starting GemFireXD Locator using peer discovery on: localhost[10334]
Starting network server for GemFireXD Locator at address localhost/127.0.0.1[1527]
Your jdbc url should be as follows:
String x = "jdbc:gemfirexd://myserver:1527/";

Creating an RMI Connector Client

I am trying to connect to MBean server. I need to write JMX Client application. This is the code used for client application. But I have got an exception related to this
Failed to retrieve RMIServer stub:
javax.naming.ServiceUnavailableException [Root exception is
java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is:
Can somebody help me to fix this.
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class SystemConfigClient {
public static final String HOST = "localhost";
public static final String PORT = "1099";
public static void main(String[] args) throws IOException, MalformedObjectNameException {
JMXServiceURL url =new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" +PORT+ "/jmxrmi");
JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
//ObjectName should be same as your MBean name
ObjectName mbeanName = new ObjectName("ifs.demo1.jmx:type=SystemConfig");
//Get MBean proxy instance that will be used to make calls to registered MBean
SystemConfigMBean mbeanProxy =
(SystemConfigMBean) MBeanServerInvocationHandler.newProxyInstance(
mbeanServerConnection, mbeanName, SystemConfigMBean.class, true);
//let's make some calls to mbean through proxy and see the results.
System.out.println("Current SystemConfig::" + mbeanProxy.doConfig());
mbeanProxy.setSchemaName("NewSchema");
mbeanProxy.setThreadCount(5);
System.out.println("New SystemConfig::" + mbeanProxy.doConfig());
//let's terminate the mbean by making thread count as 0
mbeanProxy.setThreadCount(0);
//close the connection
jmxConnector.close();
}
}
I have run this code with following arguments.
Dcom.sun.management.jmxremote Dcom.sun.management.jmxremote.port=1099
Dcom.sun.management.jmxremote.authenticate=false
Dcom.sun.management.jmxremote.ssl=false
but I got the exception of
Exception in thread "main" java.io.IOException: Failed to retrieve
RMIServer stub: javax.naming.ServiceUnavailableException [Root
exception is java.rmi.ConnectException: Connection refused to host:
localhost; nested exception is: java.net.ConnectException:
Connection refused: connect] at
javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:338)
at
javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
at
javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:207)
at com.demo1.jmx.SystemConfigClient.main(SystemConfigClient.java:29)
Caused by: javax.naming.ServiceUnavailableException [Root exception is
java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is: java.net.ConnectException: Connection refused:
connect] at
com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:101)
at
com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:185)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1886)
at
javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1856)
at
javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:257)
... 3 more Caused by: java.rmi.ConnectException: Connection refused
to host: localhost; nested exception is: java.net.ConnectException:
Connection refused: connect at
sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601) at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198)
at
sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322) at
sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source) at
com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:97)
... 8 more Caused by: java.net.ConnectException: Connection refused:
connect at java.net.PlainSocketImpl.socketConnect(Native Method) at
java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at
java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at
java.net.Socket.connect(Socket.java:529) at
java.net.Socket.connect(Socket.java:478) at
java.net.Socket.(Socket.java:375) at
java.net.Socket.(Socket.java:189) at
sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
at
sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:128)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595)
... 13 more Java Result: 1
Have you noticed that you are using the VM arguments with "D" and not "-D"? Or is it just a typo?
The correct would be:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=1099
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

Connecting error through javamail

I'm trying to connect to james server using imap protocol, but I'm getting following exception:
Exception in thread "main" javax.mail.MessagingException: Network is unreachable: connect;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:611)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at mail.main(mail.java:112)
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(PlainSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:277)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:107)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:103)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:578)
... 3 more
The James Server is already running, I don't get the reason of the above exception. Is this because James doesn't support this protocol or there any other reason?
Here's the source code of Javamail application, which is trying to connect to James Server:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class mail{
public static void main(String[] argts){
try {
Properties props=new Properties();
props.put("mail.host", "127.0.0.1 ");
props.put("mail.smtp.auth","true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("blue", "blue");
}
});
int Spam=0;
Store store=session.getStore("imap");
store.connect("localhost", "red", "red");
Folder folder=store.getFolder("IMAPFolder");
Folder folder1=store.getFolder("Spam");
boolean b=folder1.create(Spam);
System.out.println(b);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
A quick check is to see if you can talk to your IMAP server simply by using telnet:
telnet localhost 143
and if this doesn't connect, then James isn't publishing an IMAP connection (assuming the standard IMAP port).
I see from the below that you're using James 2.x. This link suggests that IMAP isn't supported.
Looks more like a network configuration error (can you ping it)
Check that 127.0.0.1 is setup correctly (and get rid of that space)

Categories