I am trying to access an amazon queue using java sdk. The queue is set in an environment with EC2 instance roles so I do not need to use credentials to access it.
Here is my code
public AWSSimpleQueueServiceClient(String queueName, String endPoint) {
try{
this.queueName = queueName;
logger.debug("Queue Name = " + this.queueName + "Endpoint = " + endPoint);
this.sqs = new AmazonSQSClient(new InstanceProfileCredentialsProvider());
if(endPoint != null) {
this.sqs.setEndpoint(endPoint);
}
} catch (Exception e) {
logger.error("Exception while creating AWS SQS Client = " + e.getMessage());
}
}
QueueName and Endpoint are got from configuration files.
I try to send/receive messages from the queue but it gives me the following exception
Exception in thread "main" com.amazonaws.services.sqs.model.QueueDoesNotExistException: The specified queue does not exist or you do not have access to it. (Service: AmazonSQS; Status Code: 400; Error Code: AWS.SimpleQueueService.NonExistentQueue; Request ID: c30b2c9a-0e62-560d-9306-628ebff676d8)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1160)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:748)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:467)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:302)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2422)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:66)
However, when I try to access the queue using the curl command, I get a response
aws sqs receive-message --queue-url <Endpoint>/031143137427/<QueueName> -- region us-east-1
{
"Messages": [
{
"Body": "Test",
"ReceiptHandle": "AQEBA49LjMDLPyyl4QKwHx9/oVFDV7mZDiOOpdKS/IC2zR3GNblg2IoHuqWBgr5iw7URCkL03Dm23TCs0Z2hB2DIzU+9qxZTOa9Ti57eiHOyAL2XAlbk7TAqGCR4lcsdSW8+LJ5zWCTkBUg5iZOqy4P0KFTfI7KtJJb2aAmeWJpApu+yJRTNAkYtdN91EcYOVFHqc1p6HJmtvvW6vJwfHB5JEbagXdfWwH3/UnJ/O36JwuFoLDp/NBRu6TO+bmYxeZmCN4GdhHuT0a11weki6Ez47Ln63G11LeQ4SFdZTC7QOWflypf8FSbG8W4JGGPZ8J8iWTkW7PGGw6DRavSu97rx3w==",
"MD5OfBody": "1f871ceacd9f4028ed371e91400efe80",
"MessageId": "0f6290d2-4554-4d96-8f93-7564ef667feb"
}
]
}
This is an exception that I get when I try it on another machine setup with EC2 roles.
Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load credentials from Amazon EC2 metadata service
at com.amazonaws.auth.InstanceProfileCredentialsProvider.handleError(InstanceProfileCredentialsProvider.java:244)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:225)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.getCredentials(InstanceProfileCredentialsProvider.java:124)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2413)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:74)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getMessagesFromQueue(AWSSimpleQueueServiceClient.java:93)
at com.ensighten.inform.jobRunner.TestJobRunner.execute(TestJobRunner.java:96)
at com.ensighten.inform.jobRunner.TestJobRunner.main(TestJobRunner.java:90)
Caused by: java.net.SocketTimeoutException: connect timed out
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 sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at com.amazonaws.internal.EC2MetadataClient.readResource(EC2MetadataClient.java:90)
at com.amazonaws.internal.EC2MetadataClient.getDefaultCredentials(EC2MetadataClient.java:55)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:186)
... 7 more
This is how I get the URL of the queue. Tried doing it two ways below. It errors out with the above exception
public String getQueueUrl() {
GetQueueUrlRequest queueUrlRequest = new GetQueueUrlRequest(this.queueName);
logger.debug("Queue Name... = " + this.queueName);
//FIRST WAY -----------> EXCEPTION on the line below
System.out.println("Queue URL .....= " + this.sqs.getQueueUrl(this.queueName));
//SECOND WAY
return this.sqs.getQueueUrl(queueUrlRequest).getQueueUrl();
}
I have been trying to figure this out for a while now. Any help is appreciated.
Related
So i have been able to register schema and produce and consume from command line .
This is how i have done .
bin/kafka-avro-console-producer --broker-list b-****.xt08nj.c5.kafka.us-east-1.amazonaws.com:9092,b-6.****.xt08nj.c5.kafka.us-east-1.amazonaws.com:9092,b-***.xt08nj.c5.kafka.us-east-1.amazonaws.com:9092 --topic AVRO-AUDIT_EVENT --property schema.registry.url=http://localhost:8081 --property value.schema='{ "type":"record", "namespace":"com.example", "name":"AuditEvents", "doc":"Avro schema for our Audit Event table", "fields":[ {"name":"ID","type":"string","doc":"id for the event"}, {"name":"VERSION","type":"string","doc":"Version of audit event "}, {"name":"ACTION_TYPE","type":"string","doc":"what action has perfomed "}, {"name":"EVENT_TYPE","type":"string","doc":"what was the event "}, {"name":"CLIENT_ID","type":"string","doc":"id of the client "}, {"name":"DETAILS","type":"string","doc":"details about the event"}, {"name":"OBJECT_TYPE","type":"string","doc":"the type of audit event object"}, {"name":"UTC_DATE_TIME","type":"string","doc":"audit event date time "}, {"name":"POINT_IN_TIME_PRECISION","type":"string","doc":"POINT_IN_TIME_PRECISION"}, {"name":"TIME_ZONE","type":"string","doc":"TIME_ZONE"}, {"name":"TIMELINE_PRECISION","type":"string","doc":"TIMELINE_PRECISION"}, {"name":"GROUP_ID","type":"string","doc":"GROUP_ID"}, {"name":"OBJECT_DISPLAY_NAME","type":"string","doc":"OBJECT_DISPLAY_NAME"}, {"name":"OBJECT_ID","type":"string","doc":"OBJECT_ID"}, {"name":"USER_DISPLAY_NAME","type":"string","doc":"USER_DISPLAY_NAME"}, {"name":"USER_ID","type":"string","doc":"USER_ID"}, {"name":"PARENT_EVENT_ID","type":"string","doc":"PARENT_EVENT_ID"}, {"name":"NOTES","type":"string","doc":"NOTES"}, {"name":"SUMMARY","type":"string","doc":"SUMMARY"}, {"name":"AUDIT_EVENT_TO_UTC_DT","type":"string","doc":"AUDIT_EVENT_TO_UTC_DT"}, {"name":"AUDIT_EVENT_TO_DATE_PITP","type":"string","doc":"AUDIT_EVENT_TO_DATE_PITP"}, {"name":"AUDIT_EVENT_TO_DATE_TZ","type":"string","doc":"AUDIT_EVENT_TO_DATE_TZ"}, {"name":"AUDIT_EVENT_TO_DATE_TP","type":"string","doc":"AUDIT_EVENT_TO_DATE_TP"} ] }'
I was able to consume from avro console as well .
Now i want to put this from java producer with some hardcoded value .
When i do that i get connection refused error .
Here is my java code .
props.setProperty("acks", "all");
props.setProperty("retries", "10");
// avro part
props.setProperty("key.serializer", StringSerializer.class.getName());
props.setProperty("value.serializer", KafkaAvroSerializer.class.getName());
props.put("schema.registry.url", "http://localhost:8081/");
Producer<String, AuditEvents> producer = new KafkaProducer<String, AuditEvents>(props);
// copied from avro examples
AuditEvents auditEvent = AuditEvents.newBuilder().setID("avro-lambda-1-5d17-136a-9749-0e710000fd04")
.setVERSION("1").setACTIONTYPE("NEW_CASE").setEVENTTYPE("WORLDCHECK")
.setCLIENTID("fgh-5d1e-17a2-9749-0e4d0000146d")
.setDETAILS(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><caseCreatedPayload><batchDetails/><caseId>0a348753-5d1e-17af-9749-0e7100006ccf</caseId><clientCaseId>case159</clientCaseId><caseName>William Mendoza</caseName><entityType>INDIVIDUAL</entityType><updateDate><dateTime>2017-07-08T22:02:32.211Z</dateTime><timeZone>UTC</timeZone><timelinePrecision>ON</timelinePrecision><pointInTimePrecision>TIME</pointInTimePrecision></updateDate><createDate><dateTime>2017-07-08T22:02:32.211Z</dateTime><timeZone>UTC</timeZone><timelinePrecision>ON</timelinePrecision><pointInTimePrecision>TIME</pointInTimePrecision></createDate><groupName>TEST_PERFORMANCE_CLIENT_2da27301-d44f-475f-92a2-1838b640d88b</groupName><nameTransposition><selected>false</selected><type>NAME_TRANSPOSITION</type><available>false</available></nameTransposition><gender>MALE</gender></caseCreatedPayload>")
.setOBJECTTYPE("CASE").setUTCDATETIME("1578469623000").setPOINTINTIMEPRECISION("TIME")
.setTIMEZONE("UTC").setTIMELINEPRECISION("ON").setGROUPID("0a348753-5d1e-17a2-9749-0e4d0000146d")
.setOBJECTDISPLAYNAME("NULL").setOBJECTID("0a348753-5d1e-17af-9749-0e7100006ccf")
.setUSERDISPLAYNAME("USER_FIRST_6cb4c322-cd3d-4809-97d3-07d2d96f10ed")
.setUSERID("USER_LAST_7e99cad9-dc1c-4770-ac4f-33c4897ce404")
.setPARENTEVENTID("parenteventid")
.setEVENTTYPE("0a348752-5d17-138e-9749-0e6a00000c7f").setNOTES("NOTES").setSUMMARY("SUMMARY IN XML")
.setAUDITEVENTTOUTCDT("1578469623000").setAUDITEVENTTODATEPITP("NULL").setAUDITEVENTTODATETZ("null")
.setAUDITEVENTTODATETP("null").build();
ProducerRecord<String, AuditEvents> producerRecord = new ProducerRecord<String, AuditEvents>(topic, auditEvent);
System.out.println("*******auditEvent****"+auditEvent);
producer.send(producerRecord, new Callback() {
#Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception == null) {
System.out.println(metadata);
} else {
exception.printStackTrace();
}
}
});
producer.flush();
producer.close();
This is the error stack trace
Error serializing Avro message: org.apache.kafka.common.errors.SerializationException
org.apache.kafka.common.errors.SerializationException: Error serializing Avro message
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:199)
at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:256)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:356)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:348)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:334)
at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.registerAndGetId(CachedSchemaRegistryClient.java:168)
at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:222)
at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:198)
at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:70)
at io.confluent.kafka.serializers.KafkaAvroSerializer.serialize(KafkaAvroSerializer.java:53)
at org.apache.kafka.common.serialization.Serializer.serialize(Serializer.java:62)
at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:894)
at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:856)
at com.amazonaws.lambda.demo.Producer_apilambdamskavro.handleRequest(Producer_apilambdamskavro.java:68)
at com.amazonaws.lambda.demo.Producer_apilambdamskavro.handleRequest(Producer_apilambdamskavro.java:20)
Please suggest what i am missing .
The way i created schema was wrong ?
You didn't specify where your code is running, but the stacktrace suggests your registry address is incorrect or the registry is not running on the address you pointed at
props.put("schema.registry.url", "http://localhost:8081/");
If it's not running on the same physical machine as the producer, you need to change the address to point at the correct location
I am using Eclipse Paho Java Client to connect. Here is my extended callback:
protected IMqttAsyncClient mClient;
private final MqttCallbackExtended mCallback = new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String brokerAddress) {
Log.d(LOG_TAG, "connectComplete " + brokerAddress);
}
#Override
public void connectionLost(Throwable ex) {
Log.d(LOG_TAG, "connectionLost", ex);
}
#Override
public void deliveryComplete(IMqttDeliveryToken deliveryToken) {
Log.d(LOG_TAG, "deliveryComplete " + deliveryToken);
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.d(LOG_TAG, "messageArrived " + topic);
}
};
And here the connecting code:
protected void connect() throws MqttException {
Log.d(LOG_TAG, "connect");
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
connectOptions.setAutomaticReconnect(false);
connectOptions.setUserName(MQTT_USERNAME);
connectOptions.setPassword(MQTT_PASSWORD.toCharArray());
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions);
Debug d = ((MqttAsyncClient) mClient).getDebug();
d.dumpClientDebug();
}
I do not use the automatic reconnect feature, but would like to handle reconnecting in my own custom code, since I need custom delays.
For testing purposes I do not start MQTT broker yet and try to connect.
I was hoping to detect the initial connection failure in the connectionLost callback method, but it does not get called.
The MqttException is not thrown either.
When I inspect the paho0.log.0 log file I see the failed connection there -
FINE 17-03-09 07:55:33.0726 al.TCPNetworkModule start 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: Failed to create TCP socket
Throwable occurred: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
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 org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
FINE 17-03-09 07:55:33.0727 nternal.ClientComms connectBG:run 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: connect failed: unexpected exception
Throwable occurred: Unable to connect to server (32103) - java.net.ConnectException: Connection refused: connect
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
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 org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
... 2 more
FINE 17-03-09 07:55:33.0732 nternal.ClientComms shutdownConnection 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: state=DISCONNECTING
FINE 17-03-09 07:55:33.0732 ernal.CommsCallback stop 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: stopped
FINE 17-03-09 07:55:33.0733 nal.CommsTokenStore quiesce 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: resp=Client is currently disconnecting (32102)
But how to detect that connection failure in my code? (So that I could initiate the later reconnection).
UPDATE:
Reported this issue as Bug #336
Currently the only way to detect the initial connect failure of an async client is to pass it one more callback:
private final IMqttActionListener mConnectionCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(LOG_TAG, "onSuccess " + asyncActionToken);
// do nothing, this case is handled in mCallback.connectComplete method
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
Log.d(LOG_TAG, "onFailure " + asyncActionToken, ex);
// initial connect has failed
}
};
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions, null, mConnectionCallback);
In my app, MongoDB 3.2.4 runs on a custom port, I want to implement logic where my app will try to reach MongoDB on a custom port and if it fails it will use the default 27018 port.
In order to do that I use the following code:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "#" + DB_URL + ":" + DB_PORT_CUS + "/" + dbName;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);
// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
// create database if doesn't exist
MongoDatabase mdb = this.mongoClient.getDatabase(dbName);
try {
this.mongoClient.getAddress();
} catch (com.mongodb.MongoSocketOpenException e) {
System.out.println("Switch to default port");
/*…use default port logic…*/
}
The problem is that this exception is not caught.
Although MongoDB throws the following exception:
com.mongodb.MongoSocketOpenException: Exception opening socket at
com.mongodb.connection.SocketStream.open(SocketStream.java:63) at
com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at
com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.net.ConnectException: Connection refused: connect at
java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
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
com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
my try-catch expression can't catch this exception.
I tried multiple approaches, such as to catch:
Exception
RuntimeException
MongoSocketOpenException
MongoException
MongoCommandException
none of them doesn't work.
My questions:
How can I check if MongoDB connection is established?
How can catch the exception MongoSocketOpenException?
I use this code to check connection:
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Database unavailable!");
mongo.close();
return;
}
Not sure here my guess would be that this.mongoClient.getAddress(); does not throw that exception, but I don't really know
EDIT: I initialized it via:
Builder builder = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3000), builder.build());
I'm trying to authenticate with the Asterisk server, but I am getting this error:
Exception in thread "main" 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:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at net.sf.asterisk.io.impl.SocketConnectionFacadeImpl.<init> SocketConnectionFacadeImpl.java:52)
at net.sf.asterisk.manager.DefaultManagerConnection.createSocket(DefaultManagerConnection.java:541)
at net.sf.asterisk.manager.DefaultManagerConnection.connect(DefaultManagerConnection.java:530)
at net.sf.asterisk.manager.DefaultManagerConnection.login(DefaultManagerConnection.java:418)
at net.sf.asterisk.manager.DefaultManagerConnection.login(DefaultManagerConnection.java:377)
at call.HelloManager.run(HelloManager.java:48)
at call.HelloManager.main(HelloManager.java:66)
Here is my code:
public class HelloManager
{
private ManagerConnection managerConnection;
public HelloManager() throws IOException
{
ManagerConnectionFactory factory = new ManagerConnectionFactory();
this.managerConnection = factory.getManagerConnection(host, port,
user, password);
}
public void run() throws IOException, AuthenticationFailedException,
TimeoutException
{
OriginateAction originateAction;
ManagerResponse originateResponse;
originateAction = new OriginateAction();
originateAction.setChannel(" SIP/2.0/UDP");
originateAction.setContext("default");
originateAction.setExten("101");
originateAction.setPriority(new Integer(1));
originateAction.setTimeout(new Integer(30000));
// connect to Asterisk and log in
managerConnection.login();
// send the originate action and wait for a maximum of 30 seconds for Asterisk
// to send a reply
// originateResponse = managerConnection.sendAction(originateAction, 30000);
// // print out whether the originate succeeded or not
// System.out.println(originateResponse.getResponse());
// and finally log off and disconnect
// managerConnection.logoff();
}
public static void main(String[] args) throws Exception
{
HelloManager helloManager;
helloManager = new HelloManager();
helloManager.run();
}
}
Can anybody help me fix this?
You need check settings in /etc/asteirsk/manger.conf
Most likly it binded to 127.0.0.1 address or disabled at all.
Also it can be issue with firewall(local or remote), port 5038 tcp have be allowed.
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.