accessing salesforce from java using web service connector - java

I am trying to connect to Salesforce from a java class (on my local machine). I have used the WSC-22.jar (webservice connector) and used the same as the library in eclipse. I have also parsed the enterprise wsdl to a jar and uploaded the library in the eclipse. I am running the below java class which is error out.
package wsc;
import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.DeleteResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class main {
static final String USERNAME = "username";
static final String PASSWORD = "password + sec token";
static EnterpriseConnection connection;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = com.sforce.soap.enterprise.Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
// run the different examples
queryContacts();
createAccounts();
updateAccounts();
deleteAccounts();
} catch (ConnectionException e1) {
System.out.println("hello world");
e1.printStackTrace();
}
}
//somemore code----
ERROR MESSAGE:
com.sforce.ws.ConnectionException: Failed to send request to
https://login.salesforce.com/services/Soap/c/26.0
at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:120)
at com.sforce.soap.enterprise.EnterpriseConnection.login(EnterpriseConnection.java:1)
at com.sforce.soap.enterprise.EnterpriseConnection.<init>(EnterpriseConnection.java:1)
at com.sforce.soap.enterprise.Connector.newConnection(Connector.java:1)
at wsc.main.main(main.java:32)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)hello world
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:570)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:411)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:525)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:966)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1031)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
at com.sforce.ws.transport.JdkHttpTransport.connectRaw(JdkHttpTransport.java:133)
at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:92)
at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:88)
at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:94)
I am unable to figure out how to solve this issue. As the error message says "Falied to connect to http://login.salesforce.com./...", should I enable some setting in Eclipse??
Regards
Sam

Are you behind a proxy ?
If so, enable proxy settings in eclipse preferences general → network

...
String proxyHost = getUserInput("Enter proxy host:");
String proxyPort = getUserInput("Enter proxy port:");
try {
...
if(proxyHost!=null && !proxyHost.trim().equals("")){
config.setProxy(proxyHost, Integer.valueOf(proxyPort));
}
...

Related

Uploading a file to testcontainer FTP server fails with Connection refused after being connected

I'm working with FTPClient against an FTP server using Testcontainers.
A reproducible code sample is here:
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import static org.assertj.core.api.Assertions.assertThat;
#Testcontainers
class FtpUtilsTest {
private static final int PORT = 21;
private static final String USER = "user";
private static final String PASSWORD = "password";
private static final int FTP_TIMEOUT_IN_MILLISECONDS = 1000 * 60;
private static final GenericContainer ftp = new GenericContainer(
new ImageFromDockerfile()
.withDockerfileFromBuilder(builder ->
builder
.from("delfer/alpine-ftp-server:latest")
.build()
)
)
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD);
#BeforeAll
public static void staticSetup() throws IOException {
ftp.start();
}
#AfterAll
static void afterAll() {
ftp.stop();
}
#Test
void test() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.setDataTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
ftpClient.setConnectTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
ftpClient.setDefaultTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
// Log
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
// Connect
try {
ftpClient.connect("localhost", ftp.getMappedPort(PORT));
ftpClient.setSoTimeout(FTP_TIMEOUT_IN_MILLISECONDS);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new AssertionError();
}
// Login
boolean loginSuccess = ftpClient.login(USER, PASSWORD);
if (!loginSuccess) {
throw new AssertionError();
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
} catch (IOException e) {
throw new AssertionError(e);
}
String remoteFile = "fileonftp";
try (InputStream targetStream = new ByteArrayInputStream("Hello FTP".getBytes())) {
assertThat(ftpClient.isConnected()).isTrue();
ftpClient.storeFile(remoteFile, targetStream);
}
}
}
This prints:
220 Welcome Alpine ftp server https://hub.docker.com/r/delfer/alpine-ftp-server/
USER *******
331 Please specify the password.
PASS *******
230 Login successful.
TYPE I
200 Switching to Binary mode.
PASV
227 Entering Passive Mode (172,17,0,3,82,15).
[Replacing PASV mode reply address 172.17.0.3 with 127.0.0.1]
then fails with:
Connection refused (Connection refused)
java.net.ConnectException: Connection refused (Connection refused)
...
at java.base/java.net.Socket.connect(Socket.java:609)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:866)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:1053)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:3816)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:3846)
What I don't understand is that it fails after successfully connecting and logging in, and returning true for isConnected.
Turns out that when removing the ftpClient.enterLocalPassiveMode(); it works, but I need it to work with the passive mode.
I guess the failure is related when switching to a different port for the passive call.
but when trying to add the ports to the withExposedPorts the container fails to start with:
Caused by: org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [55600, 55601, 55602, 55603, 55604, 55605, 55606, 55607, 55608, 55609, 55598, 55599] should be listening)
Running against a docker (docker run -d -p 21:21 -p 21000-21010:21000-21010 -e USERS="user|password" delfer/alpine-ftp-server) works.
Local docker versions:
Docker version 20.10.11, build dea9396
Docker Desktop 4.3.1
Testcontainers - appears to behave the same both on 1.16.2 and 1.15.3
Link to testcontainers discussion
As you already figured out in the comments, the tricky part about FTP passive mode is that the server uses another port (not 21) for communication.
In the docker image you're using, it's a port from the 21000-21010 range by default. So you need to publish (expose) these additional container ports. In docker run command you used -p 21000-21010:21000-21010 for that.
However, Testcontainers library is designed to publish to random host ports to avoid the problem, when a desired fixed port (or a range of ports) is already occupied on the host side.
In case of FTP passive mode random ports on the host side cause problems, because afaik you can't instruct the ftp client to override the port, which FTP server returned for the passive mode. You'd need something like ftpClient.connect("localhost", ftp.getMappedPort(PORT)); but for passive mode ports as well.
Therefore the only solution I see here is to use a FixedHostPortContainer. Even though it's marked as deprecated and not recommended to use because of the mentioned issues with occupied ports, I think this is a valid use case for it here. FixedHostPortGenericContainer allows to publish fixed ports on the host side. Something like:
private static final int PASSIVE_MODE_PORT = 21000;
...
private static final FixedHostPortGenericContainer ftp = new FixedHostPortGenericContainer<>(
"delfer/alpine-ftp-server:latest")
.withFixedExposedPort(PASSIVE_MODE_PORT, PASSIVE_MODE_PORT)
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD)
.withEnv("MIN_PORT", String.valueOf(PASSIVE_MODE_PORT))
.withEnv("MAX_PORT", String.valueOf(PASSIVE_MODE_PORT));
Keep in mind that this solution relies on the assumption that 21000 port is always free. If you're going to run this in the environment where it's not guaranteed, then you need to tweak it to find a free host port first. Like:
private static FixedHostPortGenericContainer ftp = new FixedHostPortGenericContainer<>(
"delfer/alpine-ftp-server:latest")
.withExposedPorts(PORT)
.withEnv("USERS", USER + "|" + PASSWORD);
#BeforeAll
public static void staticSetup() throws Exception {
Integer freePort = 0;
try (ServerSocket socket = new ServerSocket(0)) {
freePort = socket.getLocalPort();
}
ftp = (FixedHostPortGenericContainer)ftp.withFixedExposedPort(freePort, freePort)
.withEnv("MIN_PORT", String.valueOf(freePort))
.withEnv("MAX_PORT", String.valueOf(freePort));
ftp.start();
}
An answer similar to the accepted one but without using deprecated functionalities.
Note that we still have to use the fixed port 21000.
public static class FTPContainer extends GenericContainer<FTPContainer>
{
private static FTPContainer container;
private FTPContainer()
{
super(DockerImageName.parse("delfer/alpine-ftp-server:latest"));
}
#SuppressWarnings("resource")
public static FTPContainer getInstance()
{
if (container == null)
{
container = new FTPContainer().withEnv("USERS", "test|test|/home/").withExposedPorts(21)
.withCreateContainerCmdModifier(e -> e.getHostConfig()
.withPortBindings(new PortBinding(Ports.Binding.bindPort(21000), new ExposedPort(21000))))
.withEnv("MIN_PORT", "21000").withEnv("MAX_PORT", "21000");
}
return container;
}
#Override
public void start()
{
super.start();
}
#Override
public void stop()
{
// Handled when JVM stops
}
}
And then you can use your FTP server instance like
FTPContainer FTP = FTPContainer.getInstance();
FTP.start();

ShutdownSignalException: connection error RabbitMQ on STS4

I am attempting to connect to RabbitMQ locally on port 15672 but am getting connection error. I am unsure what could be causing this as I am attempting to learn RabbitMQ... This is tutorial 1 I can't even get running. (https://www.rabbitmq.com/tutorials/tutorial-one-java.html)
Below is the code and error. The only changes from the tutorial I have made are specifying the port and username/password. Any ideas?
package send.java;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(15672);
factory.setUsername("guest");
factory.setPassword("guest");
try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()){
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
Error
Exception in thread "main" java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:129)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:125)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:375)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:156)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1106)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1063)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1021)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1182)
at send.java.Send.main(Send.java:15)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:502)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:317)
... 7 more
Caused by: java.io.EOFException
at java.base/java.io.DataInputStream.readUnsignedByte(DataInputStream.java:294)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:91)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:184)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:598)
at java.base/java.lang.Thread.run(Thread.java:832)
Port 15672 is the (default) HTTP port for the admin (management plugin) UI.
The default AMQP port is 5672.

java.rmi.ConnectException: Connection refused to host: 192.168.0.55

I am quite a beginner with NetBeans and Java, so I'm pretty sure my questions are very basic but trying to find the solution for 2 weeks I am totally stuck
This is the problem:
I want to implement a RMI Server Client application
So first step was trying with NetBeans to have one work from the net
I used the oracle tutorial to have the first part implemented
http://docs.oracle.com/javase/tutorial/rmi/server.html
My problem is not that the client does not connect, but that the server can't even register in the port I give him. The IP in the error message is my private IP.
This is the error message I get:
Conectando a: 127.0.0.1 / 19400 / PlanificadorTalsa
ServidorPlanificadorStarter exception:
java.rmi.ConnectException: Connection refused to host: 192.168.0.55; 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:342)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at Starter.ServidorPlanificadorStarter.main(ServidorPlanificadorStarter.java:52)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 5 more
I am running windows 8.1, and disabled firewall. I am also using a security file granting all permissions
this is my java code I execute from NetBeans:
import Conexion.DatosConexion;
import Servidor.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ServidorPlanificadorStarter implements InterfazServidorPlanificador {
private static String ip;
private static String Servidor = "SERVIDORNUBE";
private static int puerto;
private static String nombreServidor;
public ServidorPlanificadorStarter(){
super();
}
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
DatosConexion datos = DatosConexion.getInstance();
ip = datos.getServiceIP(Servidor);
puerto = Integer.valueOf(datos.getServicePort(Servidor));
nombreServidor = datos.getServiceName(Servidor);
System.setProperty("java.rmi.server.hostname", ip);
System.out.println("Conectando a: " + ip + " / " + puerto + " / " + nombreServidor);
InterfazServidorPlanificador engine = new ServidorPlanificadorStarter();
InterfazServidorPlanificador stub =
(InterfazServidorPlanificador) UnicastRemoteObject.exportObject(engine, puerto);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(nombreServidor, stub);
System.out.println("ServidorPlanificador bound");
} catch (Exception e) {
System.err.println("ServidorPlanificadorStarter exception:");
e.printStackTrace();
}
}
}
The interface is as follows (very basic, as I have done nothing with it)
public interface InterfazServidorPlanificador extends Remote {
//void addObserver(RemoteObserver o) throws RemoteException;
}
Did you start RMI registry as in tutorial?
http://docs.oracle.com/javase/tutorial/rmi/running.html

Yet another RMI Issue

Before you said that, yes, I know, there are a lot of threads which cover the same issue here on Stackoverflow, but any of those solved my problem. My problem is using the RMI interface (that is mandatory for my purposes) in two distinct computers, where one provides the RMI object (Server) and one asks for the Stub and obtains a Proxy. My code is the exact copy of the one provided by the Java 7 Reference Manual by Oracle and edited by Oracle Press:
IRmi.java
import java.rmi.*;
public interface IRmi extends Remote {
double add() throws RemoteException;
}
RmiImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class RmiImpl extends UnicastRemoteObject implements IRmi {
public RmiImpl() throws RemoteException {}
public double add() { double d = 5.0; return d; }
}
Server.java
import java.net.*;
import java.rmi.*;
public class Server {
public static void main(String s[]) {
try {
RmiImpl ri = new RmiImpl();
Naming.rebind("Server",ri);
} catch (Exception e) {
System.err.println("Err");
}
}
}
Client.java
import java.rmi.*;
public class Client {
public static void main(String s[]) {
try {
IRmi itf = (IRmi)Naming.lookup("rmi://192.168.0.8/Server");
System.out.println(itf.add());
} catch (Exception e) {
e.printStackTrace();
}
}
}
After that, I compile with:
javac IRmi.java
javac RmiImpl.java
rmic RmiImpl
javac Client.java
javac Server.java
After that passage, I copy all the classes on both the client and the server, and then I run rmiregistry on the same folder where the classes were transfered. Assuming that in my local lan (192.168.0.0/255) there are two machines, where the client is 192.168.0.3 and the server 192.168.0.8 I run on those machine respectively java client and java Server, where the Client returns me the following error:
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
java.net.ConnectException: Connessione rifiutata
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.invoke(UnicastRef.java:129)
at RmiImpl_Stub.add(Unknown Source)
at Client.main(Client.java:8)
Caused by: java.net.ConnectException: Connessione rifiutata
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 5 more
For instance, In another test I've also tried to implement the server with this following code:
try {
RemImpl obj = new RemImpl(this.serv);
if (this.ob_list.size()>0) {
for (Observer ob: ob_list) {
obj.addObserver(ob);
}
}
this.myrec = (Rem) UnicastRemoteObject.exportObject(obj, 9999);
Registry registry = LocateRegistry.createRegistry(9999);
registry.rebind(this.serv, this.myrec);
//this.has_error = false;
System.out.println("Binded as "+this.serv);
} catch (RemoteException e) {
System.err.println("Remote exception catched: " + e.getMessage());
//this.has_error = true;
this.myrec = null;
}
and the client with the other following code:
try {
Registry registry = LocateRegistry.getRegistry(host);
this.myrec = (Rem) registry.lookup(service);
} catch (Exception e) {
e.printStackTrace();
}
and, in this case, the client returns me the following and different error:
java.rmi.NoSuchObjectException: no such object in table
ERROR
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:275)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:252)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:161)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.send(Unknown Source)
at rmi.lowlevel.NullSenderPolicy.send(NullSenderPolicy.java:81)
at message.policy.old.BroadcastSenderPolicy.single_send(BroadcastSenderPolicy.java:104)
at message.policy.old.AtomicBroadcastSender.fifo_send(AtomicBroadcastSender.java:54)
at message.policy.old.AtomicBroadcastNode.fifo_send(AtomicBroadcastNode.java:131)
at elements.testunit.TestPairBroadcastNodes.main(TestPairBroadcastNodes.java:20)
At this point I don't know which way to turn. Thanks in advance for any other kind suggestion.
The connection refusal seems to be a case of item A.1 in the RMI FAQ.
The NoSuchObjectInTable problem is because you're looking up the wrong Registry. You created it on port 9999 but you're looking up a different one. This can be cured by calling getRegistry(serverHost, 9999) in the client.
You should also make the Registry reference static in the server JVM.
Actually, the problem was lately solved by adding the -Djava.rmi.server.hostname=192.168.0.x argument on both client and server. Thanks for all the advices.

RabbitMQ "Hello World" example gives "Connection Refused"

II'm trying to make the "hello world" application from here: RabbitMQ Hello World
Here is the code of my producer class:
package com.mdnaRabbit.producer;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.io.IOException;
public class App {
private final static String QUEUE_NAME = "hello";
public static void main( String[] argv) throws IOException{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent" + "'");
channel.close();
connection.close();
}
}
And here what I get when implement this:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:445)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:504)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533)
at com.mdnaRabbit.producer.App.main(App.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 1
What is causing this?
I found the solution to my problem here Error in making a socket connection
To deal with it I installed RabbitMQ server. If rabbitmq-server is not installed this error will be thrown.
Make sure you have installed RabbitMQ server and it's up and running by hitting http://localhost:15672/
I got this "Connection Refused" error as well:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:588)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
at ReceiveLogs.main(ReceiveLogs.java:14)
I had made a mistake by setting the IP address from inside /etc/rabbitmq/rabbitmq-env.conf to the wrong ip address:
NODE_IP_ADDRESS=10.0.1.45
I removed this configuration parameter and the error goes away.
I solved this problem simply by executing:
sudo rabbitmq-server
Start the Rabbit MQ Server. The batch file to start this server is present under rabbitmq_server-3.6.0\sbin>rabbitmq-server.bat start then it will work.
In my case it gave me the following error trying to start the server
<Rabbit intall path>\rabbitmq_server-3.6.0\sbin>rabbitmq-server.bat start
ERROR: epmd error for host Protocol: inet_tcp: register/listen error: econnrefused: nxdomain (non-existing domain)
What I did was add in my host file the following line:
127.0.0.1 localhost
And then the rabbitmq-server started. After this I didn't get the connection refuse error anymore. Hope this helps.
Sometimes you just gotta reboot a mac. Tried all the other solutions here and other things from different questions, and as dumb as it sounds, a reboot is what finally got it back to running and able to reach http://localhost:15672/
This was after I had done a brew upgrade (which is what probably put me in a bad state).
You have to start Rabbit MQ Serever
In windows file name: RabbitMQ Service - start
You can use this code:
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class NewTaskController implements Runnable {
private final String message;
private static final String EXCHANGE_NAME = "test";
private static final String ROUTING_KEY = "test";
public NewTaskController(final String message) {
this.message = message;
}
#Override
public void run() {
//getting data from application.properties
//for the rabbit_mq configuration
ResourceBundle mRB = ResourceBundle.getBundle("application");
System.out.println("*****NewTaskController************"+mRB.getString("rabbitmq.port"));
String rabbitmq_username = mRB.getString("rabbitmq.username");
String rabbitmq_password = mRB.getString("rabbitmq.password");
String rabbitmq_hostname = mRB.getString("rabbitmq.hostname");
int rabbitmq_port = Integer.parseInt(mRB.getString("rabbitmq.port"));
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername(rabbitmq_username);
factory.setPassword(rabbitmq_password);
factory.setHost(rabbitmq_hostname);
factory.setPort(rabbitmq_port);
Connection conn;
try {
conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
String queueName = channel.queueDeclare().getQueue();
System.out.println(queueName);
channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);
System.out.println("Producing message: " + message + " in thread: " + Thread.currentThread().getName());
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes());
try {
channel.close();
} catch (TimeoutException e) {
e.printStackTrace();
}
conn.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
application.properties file:
rabbitmq.username=guest
rabbitmq.password=guest
rabbitmq.hostname=localhost
rabbitmq.port=5672
The simple fix is indeed, rabbitmq-server, if you already have RabbitMQ installed locally.
I encountered this issue as a firewall issue after migrating from Mac OS X Sierra to High Sierra. I already had RabbitMQ installed. However, I kept getting this Connection Refused error. I had to do the following:
brew uninstall rabbitmq
brew install rabbitmq
rabbitmq-server
(and allow firewall permissions)
Run app locally.

Categories