I am using Java8 and have a Chat Server that works perfectly on my localhost, but when I deploy it to an OpenShift server, I get the following error:
java.net.SocketException: Permission denied
2016-09-05 10:36:11,300 INFO [stdout] (Thread-125) Starting Chat server on localhost:8000 ...
2016-09-05 10:36:13,194 ERROR [stderr] (Thread-125) Exception in thread "Thread-125" java.net.SocketException: Permission denied
2016-09-05 10:36:13,194 ERROR [stderr] (Thread-125) at sun.nio.ch.Net.bind0(Native Method)
2016-09-05 10:36:13,195 ERROR [stderr] (Thread-125) at sun.nio.ch.Net.bind(Net.java:433)
2016-09-05 10:36:13,195 ERROR [stderr] (Thread-125) at sun.nio.ch.Net.bind(Net.java:425)
2016-09-05 10:36:13,195 ERROR [stderr] (Thread-125) at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
2016-09-05 10:36:13,195 ERROR [stderr] (Thread-125) at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
2016-09-05 10:36:13,196 ERROR [stderr] (Thread-125) at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:125)
2016-09-05 10:36:13,196 ERROR [stderr] (Thread-125) at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:476)
2016-09-05 10:36:13,196 ERROR [stderr] (Thread-125) at io.netty.channel.DefaultChannelPipeline$HeadHandler.bind(DefaultChannelPipeline.java:1000)
2016-09-05 10:36:13,196 ERROR [stderr] (Thread-125) at io.netty.channel.DefaultChannelHandlerContext.invokeBind(DefaultChannelHandlerContext.java:463)
2016-09-05 10:36:13,197 ERROR [stderr] (Thread-125) at io.netty.channel.DefaultChannelHandlerContext.bind(DefaultChannelHandlerContext.java:448)
2016-09-05 10:36:13,197 ERROR [stderr] (Thread-125) at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:842)
2016-09-05 10:36:13,197 ERROR [stderr] (Thread-125) at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:195)
2016-09-05 10:36:13,197 ERROR [stderr] (Thread-125) at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:338)
2016-09-05 10:36:13,198 ERROR [stderr] (Thread-125) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:370)
2016-09-05 10:36:13,198 ERROR [stderr] (Thread-125) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:353)
2016-09-05 10:36:13,198 ERROR [stderr] (Thread-125) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
2016-09-05 10:36:13,198 ERROR [stderr] (Thread-125) at java.lang.Thread.run(Thread.java:745)
I have looked at the OpenShift web sockets guide here, which says port 8000 should be used. But I still get the error.
On Openshift I am running my chat server on a WildFly Application Server 10 cartridge.
Any advise appreciated.
Here is my code:
WebAppInitializer.java
try {
new Thread() {
public void run() {
com.jobs.spring.chat.Server chatServer = new com.jobs.spring.chat.Server();
chatServer.startServer();
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
Server.java
import java.net.Socket;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* https://blog.openshift.com/paas-websockets/
* #author Richard
*
*/
public class Server {
//private static final String SERVER = "localhost";
private static final String SERVER = "jbosswildfly-easyjobs.rhcloud.com";
private static final Integer PORT = 8000;
public static void main(String[] args) {
startServer();
}
public static void startServer() {
Configuration config = new Configuration();
config.setHostname(SERVER);
config.setPort(PORT);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(new ConnectListener() {
#Override
public void onConnect(SocketIOClient client) {
System.out.println("onConnected");
client.sendEvent("chat_message:message", new Message("Welcome to the chat!"));
}
});
server.addDisconnectListener(new DisconnectListener() {
#Override
public void onDisconnect(SocketIOClient client) {
System.out.println("onDisconnected");
}
});
server.addEventListener("chat_message:send", String.class, new DataListener<String>() {
#Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
Message message = null;
try {
message = new ObjectMapper().readValue(data.toString(), Message.class);
} catch (Exception e) {
e.printStackTrace();
}
message.setDate(System.currentTimeMillis());
server.getBroadcastOperations().sendEvent("chat_message:message", message);
}
});
System.out.println("Starting Chat server on " + SERVER + ":" + PORT+" ...");
server.start();
System.out.println("Chat server started");
System.out.println("Chat server Environment Info: " + System.getenv());
try {
Socket socket = new Socket(SERVER, PORT);
printSocketInformation(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Prints debug output (to stdout) for the given Java Socket.
*/
public static void printSocketInformation(Socket socket) {
try {
System.out.format("Port: %s\n", socket.getPort());
System.out.format("Canonical Host Name: %s\n", socket.getInetAddress().getCanonicalHostName());
System.out.format("Host Address: %s\n\n", socket.getInetAddress().getHostAddress());
System.out.format("Local Address: %s\n", socket.getLocalAddress());
System.out.format("Local Port: %s\n", socket.getLocalPort());
System.out.format("Local Socket Address: %s\n\n", socket.getLocalSocketAddress());
System.out.format("Receive Buffer Size: %s\n", socket.getReceiveBufferSize());
System.out.format("Send Buffer Size: %s\n\n", socket.getSendBufferSize());
System.out.format("Keep-Alive: %s\n", socket.getKeepAlive());
System.out.format("SO Timeout: %s\n", socket.getSoTimeout());
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this link OpenShift talk about port binding and proxies. I don't really understand all of it. It looks like I should use port 8000 (which I am), but I am not clear what hostname I should use. I am using my application url name (jbosswildfly-easyjobs.rhcloud.com). Is that correct?
If I change the address to, http://jbosswildfly-easyjobs.rhcloud.com (i.e. prefix http://) I get the following error:
java.net.SocketException: Unresolved address
I was trying to find out solution. I have got some solutions. All are suggesting to add -Djava.net.preferIPv4Stack=true to the VM options.
Atlassian Documentation also got the root cause and solution given below:
Cause
This is one of the known issues with Java 7, as per this post.
This can also be caused by any anti-virus or firewall software
installed on the server.
Resolution
Use the -Djava.net.preferIPv4Stack=true JVM system property to help
enable support for IPv4 on Java 7.
Check that anti-virus and firewall software on the server is not
blocking Stash's ability to connect to the mail server.
This solution is for Java 7, but you are using Java 8. So I lookup your stacktrace. There is a line
at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:125)
Which is telling that you are using netty.
But netty has some requirement on version basis. There is also some limitations.
JDK 5 (Netty 3.x) or 6 (Netty 4.x) is enough. Some components such as
HTTP/2 might have more requirements
Requirements for Netty 4.x(link)
Java does not currently support ALPN or NPN (there is a tracking issue so go upvote it!). For lack of support in the JDK we need to
use the Jetty-ALPN (or Jetty-NPN if on Java < 8) bootclasspath
extension for OpenJDK. To do this, add a Xbootclasspath JVM option
referencing the path to the Jetty alpn-boot jar.
java -Xbootclasspath/p:/path/to/jetty/alpn/extension.jar ...
Note that you must use the release of the Jetty-ALPN jar specific
to the version of Java you are using.
JDK Ciphers
Java 7 does not support the cipher suites recommended by the HTTP2 RFC. To address this we suggest servers use Java 8 where
possible or use an alternative JCE implementation such as Bouncy
Castle. If this is not practical it is possible to use other
ciphers but you need to ensure that the services you intend to call
also support these ciphers forbidden by the HTTP/2 RFC and have
evaluated the security risks of doing so.
Enabling ALPN or NPN
The SslContextBuilder has a setter for an ApplicationProtocolConfig which is used to configure ALPN or NPN.
See the HTTP/2 examples for ALPN and SPDY examples for NPN
usage.
For details description, you can go through this link.
Suggestions:
So check your netty version and take decision according above issues. Or use JDK 7 if possible.
The linked blog post says that you can connect to websockets on OpenShift using ports 8000 and 8443. However, the server itself needs to be bound only to port 8080 and then you can connect externally to the ws ports above. This diagram that you have already found explains the configuration.
WildFly is using 8080 already, so you may want to use the DIY cartridge to deploy your app (don't forget to disable the default ruby server in the start action hook that is running on 8080) or be inspired here.
Related
I've already researched the topic for a few days but none of the answers I found online did the trick for me.
Context: I've got a Spring Boot web application which sends automatic emails notifications using Java Mail API and Spring Boot Starter Mail.
It is using GMail SMTP server with a GSuite account. I recently upgraded to use Spring 5.0.6 and Spring Boot 2.0.2 and the email sending stopped working.
A few clues:
the Java code sending the email is the same as before
Gmail SMTP still works correctly (from another VM using older version of the application with the same settings and authentication, the emails are sent properly).
unless I am missing something, the application configuration remains the same as before
The things that have changed:
upgrade to Spring 5.0.6
upgrade to Spring Boot 2.0.2
changes in many places in the Java code to match this upgrades and add features in other parts of the app
The IP address of the VM is different than before (AWS EC2 instance)
Here are the relevant dependencies in pom.xml :
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Here is the application.yml relevant to Spring mail:
spring:
mail:
host: ${FT_MAIL_SMTP_HOST}
port: ${FT_MAIL_SMTP_PORT}
username: ${FT_MAIL_SMTP_USERNAME}
password: ${FT_MAIL_SMTP_PASSWORD}
debug: false
properties:
mail:
smtp:
starttls:
enable: ${FT_MAIL_SMTP_STARTTLS}
required: ${FT_MAIL_SMTP_TLSREQUIRED}
auth: ${FT_MAIL_SMTP_AUTH}
connectiontimeout: ${FT_MAIL_SMTP_CONN_TIMEOUT}
timeout: ${FT_MAIL_SMTP_TIMEOUT}
writetimeout: ${FT_MAIL_SMTP_WRITE_TIMEOUT}
These variables are defined in the environment:
FT_MAIL_SMTP_HOST=smtp.gmail.com
FT_MAIL_SMTP_PORT=587
FT_MAIL_SMTP_USERNAME=myaccount#myapp.com
FT_MAIL_SMTP_PASSWORD=mypassword
FT_MAIL_SMTP_STARTTLS=true
FT_MAIL_SMTP_TLSREQUIRED=true
FT_MAIL_SMTP_AUTH=true
FT_MAIL_SMTP_CONN_TIMEOUT=5000
FT_MAIL_SMTP_TIMEOUT=5000
FT_MAIL_SMTP_WRITE_TIMEOUT=5000
Here is the Spring #Service used to send the email (unchanged):
#Service
public class EmailServiceImpl {
#Autowired
public JavaMailSender emailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value("${myapp.mail.from}")
private String fromAddress;
#Value("${myapp.mail.replyto}")
private String replyToAddress;
public void sendTemplatedMessage(String template, String to, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, fromAddress, replyToAddress, subject, model);
}
public void sendTemplatedMessage(String template, String to, String from, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, from, replyToAddress, subject, model);
}
private void sendTemplatedMessage(String template, String to, String from, String replyTo, String subject, Map<String, Object> model) throws MailException, MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
//helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png"));
Context context = new Context();
context.setVariables(model);
String html = templateEngine.process(template, context);
helper.setTo(to);
helper.setFrom(from);
helper.setReplyTo(from);
helper.setSubject(subject);
helper.setText(html, true);
emailSender.send(message);
}
public void sendSimpleMessage(String to, String from, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setFrom(from);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here is the error I get when trying to send an email:
04:42:19.900 [https-jsse-nio-443-exec-3] ERROR c.f.controller.StayController - Could not send Guest confirmation email to gfgorostidi#protonmail.com
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
I have tried setting an incorrect SMTP server or bad credentials and this made the connection fail, so I assumed the server and credentials are correct as they are, and the error happens after a successful connection.
The account used hasn't reached its limit, as another VM uses the same credentials and sends emails without problem.
I've tried changing "Start TLS" settings to false and use port 465 instead, but this isn't working either.
Any help is appreciated !! Thanks in advance!
After much more trial and error with the configuration, I found out that it required an application property "spring.mail.protocol" in the configuration.
I've added the line protocol: smtp in application.yml:
spring:
mail:
protocol: smtp
And that fixed the read timeout issue, email are now sent properly. Hope that may help someone in the future.
I did face the same issue, but my scenario was a bit different
I was trying to send in a schedule manner using quartz
When I did not use Quartz, it was all working fine, but with quartz it started failing
The above solution did not help me, but pointed me in direction of looking at the properties that I had set.
Increasing the connection timeout did the job for me
Thus changed the application properties
from:
spring.mail.properties.mail.smtp.timeout=3000
to:
spring.mail.properties.mail.smtp.timeout=25000
Hope it works for others as well
I'm getting similar error to this link1.
When I post(client to server) a small xml via REST, everything works fine. Unfortunately I'm getting an error while I'm posting some bigger xmls, when the connection lasts longer than 10/15 min. (I assume It's some kind of timeout)
I corrected my SSL certs as it was mentioned in the link1 - configureClient() method is the same in my case as the solution from the one in the link1.
I added also System.setProperty("java.net.preferIPv4Stack" , "true"); - sometimes it solves Connection reset
Essential info:
Error: javax.ws.rs.ProcessingException: java.net.SocketException: Connection reset
Method: REST POST
Java version: 7
Engine: Jersey 2.x
Side: Client
System: Windows 7
My client:
System.setProperty("java.net.preferIPv4Stack" , "true");
RestMethodes restMethodes = new RestMethodes();
ClientConfig config = new ClientConfig();
config = config.property(ClientProperties.CONNECT_TIMEOUT, 0);
config = config.property(ClientProperties.READ_TIMEOUT, 0);
config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
Client client = configureClient(config);
client.register(HttpAuthenticationFeature.basic(USER, PASS));
WebTarget target = client.target(SERVER_URL + "/bundles/assets");
Invocation.Builder responseInvocation = target.request(MediaType.APPLICATION_JSON);
// My exception is thrown there
Response response = responseInvocation.post(Entity.xml(assetsString));
String entity = response.readEntity(String.class);
//entity = jsonPrettyPrinter(entity);
if (entity.isEmpty() || entity.equals("")) {
log.info("[POST ASSETS] Failed : Response is empty");
}
Response.StatusType codeName = response.getStatusInfo();
int code = response.getStatus();
if (code != 200) {
log.error("[POST ASSETS] Failed : HTTP error code : " + response.getStatus() + "\n" + entity);
response.close();
} else {
log.info("[POST ASSETS] RESPONSE CODE ID : " + code + " CODE NAME : " + codeName);
log.info("[POST ASSETS] RESPONSE : " + entity);
response.close();
}
client.close();
My ERROR
Exception in thread "main" javax.ws.rs.ProcessingException: java.net.SocketException: Connection reset
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at com.sas.spl.saslineagebridges.test.PostTester.main(PostTester.java:61)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:675)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1569)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:399)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
... 11 more
EDIT:
I forgot to mention that I managed to post my request via CURL from bash with infinity timeout and keep alive, so It shouldn't be the servers issue. The CURL REST post took 24 min. and my java client throws connection reset after 15 min. In my opinion It might be my fault.
You are facing a timeout issue, although your client seems well configured. This timeout can be caused by any firewall, proxy, load-balancer, or even the server itself if it is running a web server like Apache in front of the application server. Please check what is in-between your client and the application server, and set timeouts accordingly everywhere.
It doesn't mean that you can't do nothing on the client itself, but it's much more difficult to solve there.
On Windows you will need to enable the TCP keep-alives, first.
After, according to the Client Transport you are using, we will try to add TCP keep-alives to the sockets built by the underlying factory, something similar that we know possible on Axis clients. This solution is more time-consuming for you.
So i have this code to connect to openfire
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setUsernameAndPassword(loginUser, passwordUser);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost(serverAddress);
config.setPort(5222);
config.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(config.build());
ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
System.out.println("Reconnection enabled : " + ReconnectionManager.getInstanceFor(connection).isAutomaticReconnectEnabled());
ConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
but when i try to connect i get this error :
org.jivesoftware.smack.XMPPException$StreamErrorException: internal-server-error You can read more about the meaning of this stream error at http://xmpp.org/rfcs/rfc6120.html#streams-error-conditions
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1007)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:948)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:963)
at java.lang.Thread.run(Thread.java:744)
EDIT : Openfire's log :
Warn log :
2016.06.13 11:06:31 org.apache.mina.core.filterchain.DefaultIoFilterChain - Unexpected exception from exceptionCaught handler.
java.lang.NoSuchMethodError: java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;
at org.jivesoftware.openfire.roster.Roster.broadcastPresence(Roster.java:628)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.broadcastUpdate(PresenceUpdateHandler.java:309)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:163)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:138)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:202)
at org.jivesoftware.openfire.PresenceRouter.handle(PresenceRouter.java:144)
at org.jivesoftware.openfire.PresenceRouter.route(PresenceRouter.java:80)
at org.jivesoftware.openfire.spi.PacketRouterImpl.route(PacketRouterImpl.java:88)
at org.jivesoftware.openfire.SessionManager$ClientSessionListener.onConnectionClose(SessionManager.java:1267)
at org.jivesoftware.openfire.nio.NIOConnection.notifyCloseListeners(NIOConnection.java:266)
at org.jivesoftware.openfire.nio.NIOConnection.close(NIOConnection.java:248)
at org.jivesoftware.openfire.nio.ConnectionHandler.exceptionCaught(ConnectionHandler.java:162)
i tried to connect to a local openfire server(windows), i succeded, but I fail when i try to connect to an ubuntu openfre server.
Any help would be appreciated.
Newer versions of Openfire need Java 8 (or higher).
To be precise : openfire needs oracle jre 8 NOT Openjdk
We have several server side components in our architecture. Each component uses JMX to expose various internal attributes. Initialization is done as follows:
try {
Registry registry = null;
for(int i = _serverInfo.getJMXStartPort(); i <= _serverInfo.getJMXEndPort(); i++) {
try {
registry = LocateRegistry.createRegistry(i);
if(registry != null) {
_statusPort = i;
logger.info("Using JMX port: "+_statusPort);
break;
}
} catch (Exception e) {
_statusPort++;
}
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
_abstractServiceController = new AbstractServiceController(this);
ObjectName mbeanName = new ObjectName("MyServer:name=MyServer Service");
mbs.registerMBean(_abstractServiceController, mbeanName);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:"+_statusPort+"/jmxrmi");
JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, System.getenv(), mbs);
cs.start();
} catch (Throwable e) {
logger.error("Unable to register MBean with JMX");
e.printStackTrace();
}
I guess I have two questions.
Does this look right?
The bigger question is, while this runs fine on java 1.6 (each subsequent server on a host uses the next available port, since LocateRegistry.createRegistry(i) throws an exception if the port is unavailable), not so on 1.7. As a result, we get the following exception when the second server attempts to JMXConnectorServer.start(). Does anyone know if the behavior changed for createRegistry? If so, is there something else we should do?
2013-02-07 15:34:28,451 INFO [main] Using JMX port: 9500
2013-02-07 15:34:28,929 ERROR [main] Unable to register MBean with JMX
java.io.IOException: Cannot bind to URL [rmi://:9500/jmxrmi]: javax.naming.NameAlreadyBoundException: jmxrmi [Root exception is java.rmi.AlreadyBoundException: jmxrmi]
at javax.management.remote.rmi.RMIConnectorServer.newIOException(RMIConnectorServe.java:826)
at javax.management.remote.rmi.RMIConnectorServer.start(RMIConnectorServer.java:431)
at com.theatre.services.framework.AbstractService.run(AbstractService.java:306)
at com.theatre.services.reporttree.TreeServerImpl.run(TreeServerImpl.java:690)
at com.theatre.services.framework.Launcher.main(Launcher.java:99)
Caused by: javax.naming.NameAlreadyBoundException: jmxrmi [Root exception is java.rmi.AlreadyBoundException: jmxrmi]
at com.sun.jndi.rmi.registry.RegistryContext.bind(RegistryContext.java:139)
at com.sun.jndi.toolkit.url.GenericURLContext.bind(GenericURLContext.java:226)
at javax.naming.InitialContext.bind(InitialContext.java:419)
at javax.management.remote.rmi.RMIConnectorServer.bind(RMIConnectorServer.java:643)
at javax.management.remote.rmi.RMIConnectorServer.start(RMIConnectorServer.java:426)
... 3 more
Caused by: java.rmi.AlreadyBoundException: jmxrmi
at sun.rmi.registry.RegistryImpl.bind(RegistryImpl.java:131)
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:390)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:248)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:273)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:251)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:377)
at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
at com.sun.jndi.rmi.registry.RegistryContext.bind(RegistryContext.java:137)
... 7 more
Does this look right?
No. Creating a Registry can fail for several reasons, not just because the port is in use.
registry cannot be null after createRegistry(), so testing for it is pointless.
If you're trying to find a free port, just open (and close) a ServerSocket(). Then create the Registry on that port if it worked.
The bigger question is, while this runs fine on java 1.6 (each subsequent server on a host uses the next available port, since LocateRegistry.createRegistry(i) throws an exception if the port is unavailable), not so on 1.7.
See above. Creating a Registry can also fail if there is already one running on that port, in any JDK. In earlier JDKs it would fail if there was one running on any port in the same JVM.
I am learning about Java RMI and have an example code to show how RMI can be used to pass objects to another virtual machines over a network.
Here are the classes and code I am using;
//interface
import java.rmi.*;
public interface MyRemote extends Remote
{
public String sayHello() throws RemoteException;
}
//My Remote Implementation Class
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote
{
public String sayHello()
{
return "Server says, 'Hey' ";
}
public MyRemoteImpl() throws RemoteException
{
}
public static void main (String[] args)
{
try
{
MyRemote service = new MyRemoteImpl();
Naming.rebind("Remote Hello", service);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
//My Remote Client Class
import java.rmi.*;
public class MyRemoteClient
{
public static void main (String [] args)
{
new MyRemoteClient().go();
}
public void go()
{
try{
MyRemote service = (MyRemote) Naming.lookup("rmi://127.0.0.1/Remote Hello");
String s = service.sayHello();
System.out.println(s);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
I keep getting java.net.MalformedURLException: invalid URL String: rmi://127.0.0.1/Remote Hello which I know is due to the 'Naming.lookup("rmi://127.0.0.1/Remote Hello")' code in the last class.
I have installed tomcat and tried placing the files in a directory, trying to get it to run on my local machine but I have had no joy.
I have created a JAR file of my project and tried placing that in a directory also and still no luck. I have heard about war files but currently the book I am learning from hasnt come to that yet...
Any tips on how I can get around this without the exception being called? Am I placing the files incorrectly in Tomcat? I have placed them in my C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps directory.
Any help or tips will be greatly appreciated.
UPDATE
Thanks for the advice, the String exception seems to have gone away but now I am lumbered with this.
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:340)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Naming.java:101)
at MyRemoteClient.go(MyRemoteClient.java:13)
at _SHELL57.run(_SHELL57.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:623)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:316)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:177)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:164)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:154)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:352)
at java.net.Socket.connect(Socket.java:569)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.(Socket.java:416)
at java.net.Socket.(Socket.java:199)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:146)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
2 things:
Change the name of the remote object to something without a space.
Are you running the server code first?
What does Tomcat have to do with RMI? Tomcat is a servlet/JSP engine that listens for HTTP requests on port 8080 by default.
RMI is a totally different protocol that has nothing to do with HTTP. The RMI daemon uses port 1099 by default.
I'd recommend looking at this.
Check your /etc/hosts file at the server. It should map localhost to 127.0.0.1 and your real hostname to your real IP address. If you have a configuration where you need the other way round, set the system property java.rmi.server.hostname to the correct IP address at the server JVM before exporting the remote object.