I've been working for some time with aws java API with not so many problems. Currently I'm using the library 1.5.2 version.
When I'm iterating the objects inside a folder with the following code:
AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(MyClass.class.getResourceAsStream("AwsCredentials.properties")));
String s3Key = "folder1/folder2";
String bucketName = Constantes.S3_BUCKET;
String key = s3Key +"/input_chopped/";
ObjectListing current = s3.listObjects(new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(key));
boolean siguiente = true;
while (siguiente) {
siguiente &= current.isTruncated();
contador += current.getObjectSummaries().size();
for (S3ObjectSummary objectSummary : current.getObjectSummaries()) {
S3Object object = s3.getObject(new GetObjectRequest(bucketName, objectSummary.getKey()));
System.out.println(object.getKey());
}
current=s3.listNextBatchOfObjects(current);
}
Gist: Link: https://gist.github.com/fgblanch/6038699
I'm getting the following exception:
INFO (AmazonHttpClient.java:358) - Unable to execute HTTP request: Timeout waiting for connection from pool
org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
at org.apache.http.impl.conn.PoolingClientConnectionManager.leaseConnection(PoolingClientConnectionManager.java:232)
at org.apache.http.impl.conn.PoolingClientConnectionManager$1.getConnection(PoolingClientConnectionManager.java:199)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:315)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:199)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:2994)
at com.amazonaws.services.s3.AmazonS3Client.getObject(AmazonS3Client.java:918)
at com.madiva.segmentacion.tests.ListaS3.main(ListaS3.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network.
Error Message: Unable to execute HTTP request: Timeout waiting for connection from pool
Any idea how to avoid this error. It only happens in folders with a number of object , in this case there were 463 files inside. Thanks
I've found that S3Object opens a connection for each object. That are not liberated even if the object is garbage collected so it is needed to execute object.close(), in order to liberate the connection to the pool.
So the corrected code would be:
for (S3ObjectSummary objectSummary : current.getObjectSummaries()) {
S3Object object = s3.getObject(new GetObjectRequest(bucketName, objectSummary.getKey()));
System.out.println(object.getKey());
object.close();
}
Check if HttpResponseHandler is closing connections from the pool.
AmazonHttpClient has the paramter 'leaveHttpConnectionOpen' which indicates that the connection should be closed or not.
Related
my code here:
function MsgReceivedInPastHourchannelId,connectorID, status) {
var client = new com.mirth.connect.client.core.Client('https://127.0.0.1:443/');
try{
var loginStatus = client.login('userID', 'psw');
} catch(ex) {
client.close();
throw 'Unable to log-on the server , Error: ' + ex.message;
}
var filter = new com.mirth.connect.model.filters.MessageFilter;
var calendar = java.util.Calendar;
var startDate = new calendar.getInstance();
var endDate = new calendar.getInstance();
..
.. logic to set start/end date
..
filter.setStartDate(startDate);
filter.setEndDate(endDate);
var statuses = new java.util.HashSet();
var Status = com.mirth.connect.donkey.model.message.Status;
var list = Lists.list().append(connectorID);
var metricStatus = Status.SENT;
statuses.add(metricStatus);
filter.setStatuses(statuses);
filter.setIncludedMetaDataIds(list) ;
var nCount =client.getMessageCount(channelId, filter);
client.close();
return nCount
}
reference :
Mirth getMessageCount using Javascript not working
Mostly it works fine, but it randomly throw exception at line number 218, this is
var client = new com.mirth.connect.client.core.Client('https://127.0.0.1:443/')
anyone have experience or solution to get rid of such error:
[2021-06-30 02:00:02,000] ERROR (com.mirth.connect.connectors.js.JavaScriptDispatcher:193):
Error evaluating JavaScript Writer (JavaScript Writer "Submit Hx channel status to DataDog" on channel 1xxxxxxxxxxxxxxxx4).
com.mirth.connect.server.MirthJavascriptTransformerException: CHANNEL:
ChannelStatus-Poller-CountCONNECTOR:
Submit Hxchannel status to DataDogSCRIPT SOURCE:
JavaScript WriterSOURCE CODE:
218: var client = new com.mirth.connect.client.core.Client('https://127.0.0.1:443/') 221: // log on to the server222:
try{LINE NUMBER: 218 DETAILS:
Wrapped java.lang.IllegalStateException: zip file closed
at a7fa25a9-af95-4410-bb4f-f4f08ae0badb:218 (MsgReceivedInPastHour)
at a7fa25a9-af95-4410-bb4f-f4f08ae0badb:1013 (doScript)
at a7fa25a9-af95-4410-bb4f-f4f08ae0badb:1033
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:184)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:122)
at com.mirth.connect.server.util.javascript.JavaScriptTask.call(JavaScriptTask.java:113)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)Caused by: java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(ZipFile.java:686)
at java.util.zip.ZipFile.access$200(ZipFile.java:60)
at java.util.zip.ZipFile$ZipEntryIterator.hasNext(ZipFile.java:508)
at java.util.zip.ZipFile$ZipEntryIterator.hasMoreElements(ZipFile.java:503)
at java.util.jar.JarFile$JarEntryIterator.hasNext(JarFile.java:253)
at java.util.jar.JarFile$JarEntryIterator.hasMoreElements(JarFile.java:262)
at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:30)
at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:26)
at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:141)
at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:136)
at org.reflections.Reflections.scan(Reflections.java:240)
at org.reflections.Reflections.scan(Reflections.java:204)
at org.reflections.Reflections.<init>(Reflections.java:129)
at org.reflections.Reflections.<init>(Reflections.java:170)
at org.reflections.Reflections.<init>(Reflections.java:143)
at com.mirth.connect.client.core.Client.<init>(Client.java:176)
at com.mirth.connect.client.core.Client.<init>(Client.java:143)
at sun.reflect.GeneratedConstructorAccessor159.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.mozilla.javascript.MemberBox.newInstance(MemberBox.java:159)
at org.mozilla.javascript.NativeJavaClass.constructInternal(NativeJavaClass.java:266)
at org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:205)
at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:166)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1525)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:815)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:109)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:405)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3508)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:120)
at com.mirth.connect.server.util.javascript.JavaScriptTask.executeScript(JavaScriptTask.java:150)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:149)
... 6 more
Issue could not be solved in Mirth connector Admin environment, to solve this issue, I used DB query instead.
go to Mirth DB, you can find related tables and it is more safe to query such DB.
The reason not to invoke,
answer from Mirth slack general channel,
"When using the Client class you're pretty much looping back to the server, since all the code is executed on the server anyways."
so always didn't com.mirth.connect.client.core.Client class in Mirth code.
Issue closed.
I'm trying to decode testnet transaction using bitcoinj 0.14.7.
This is HEX of the transaction I'm trying to decode:
02000000000101ef4c1c3c60028b050a5798265c0b37719418dd71b0621e76a68a47d5d9eef55f000000001716001467d7c32c0dad98bf8dd3dea81cbb1dbd4ea4afb5feffffff02b7df02000000000017a914ebb55a85454dc15589b8a87bab4b438892b54c0c87b0ad0100000000001976a914140b85a1c430c8f4fd1f91ae1c7451902b8ce76c88ac024730440220359623836f97e9e4c04917455ed2f9fb2343b0bf96853d47313b0c96d828c889022046da37bfda03cf3481e3ef5c5b5e655d6fd280c2aec2831b6494a8207b76655b01210224c44e1af98b5c28ebf822b65e4a2872d0780b4b6935b3100f60d3ac3b78cb00b2f81500
When I go to the blockcipher https://live.blockcypher.com/btc/decodetx/ and decode the transaction there - it's decoded no problem. But when I'm trying to do this:
Transaction tx = new Transaction(params, HexUtils.hexToBytes(txHex));
LOGGER.info(tx.toString());
it prints
4c67f1e1b10b063210e59400466383fb18634c05430d4f53795a16216dd34ffd
version 2
INCOMPLETE: No inputs!
out [exception: Push of data element that is larger than remaining data]
prps UNKNOWN
Also, I checked my code against master and it worded like a charm! Here is the output:
65b47da760fb781a80e8607e19c82454f12c4ee8dd699045d4e96c869e07bf25
version 2
time locked until block 1439922
in PUSHDATA(22)[001467d7c32c0dad98bf8dd3dea81cbb1dbd4ea4afb5]
witness:30440220359623836f97e9e4c04917455ed2f9fb2343b0bf96853d47313b0c96d828c889022046da37bfda03cf3481e3ef5c5b5e655d6fd280c2aec2831b6494a8207b76655b01 0224c44e1af98b5c28ebf822b65e4a2872d0780b4b6935b3100f60d3ac3b78cb00
outpoint:5ff5eed9d5478aa6761e62b071dd189471370b5c2698570a058b02603c1c4cef:0
sequence:fffffffe
out HASH160 PUSHDATA(20)[ebb55a85454dc15589b8a87bab4b438892b54c0c] EQUAL 0.00188343 BTC
P2SH addr:2NEjY32rnrCdi8Cve6yJ4RaPanugBnJ8fme
out DUP HASH160 PUSHDATA(20)[140b85a1c430c8f4fd1f91ae1c7451902b8ce76c] EQUALVERIFY CHECKSIG 0.0011 BTC
P2PKH addr:mhLwcTEoquZcAjT34fD4uPySUAdK77uqvL
prps UNKNOWN
Please, help!
Your code just creating a transaction object so that's not enough.
Your requirement is fetching a transaction from block. So You need to connect a testnet node. Just create a PeerGroup connect local or remote bitcoin testnet node.
Check that example below.
final NetworkParameters params = TestNet3Params.get();
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.start();
// Alternatively you can connect your localhost or another working testnet node
peerGroup.addAddress(new PeerAddress(params, "testnet-seed.bitcoin.jonasschnelli.ch", 18333));
peerGroup.waitForPeers(1).get();
Peer peer = peerGroup.getConnectedPeers().get(0);
Sha256Hash txHash = Sha256Hash.wrap(hexString);
ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
System.out.println("Waiting for node to send us the requested transaction: " + txHash);
Transaction tx = future.get();
System.out.println(tx);
We're having some trouble trying to implement a Pool of SftpConnections for our application.
We're currently using SSHJ (Schmizz) as the transport library, and facing an issue we simply cannot simulate in our development environment (but the error keeps showing randomly in production, sometimes after three days, sometimes after just 10 minutes).
The problem is, when trying to send a file via SFTP, the thread gets locked in the init method from schmizz' TransportImpl class:
#Override
public void init(String remoteHost, int remotePort, InputStream in, OutputStream out)
throws TransportException {
connInfo = new ConnInfo(remoteHost, remotePort, in, out);
try {
if (config.isWaitForServerIdentBeforeSendingClientIdent()) {
receiveServerIdent();
sendClientIdent();
} else {
sendClientIdent();
receiveServerIdent();
}
log.info("Server identity string: {}", serverID);
} catch (IOException e) {
throw new TransportException(e);
}
reader.start();
}
isWaitForServerIdentBeforeSendingClientIdent is FALSE for us, so first of all the client (we) send our identification, as appears in logs:
"Client identity String: blabla"
Then it's turn for the receiveServerIdent:
private void receiveServerIdent() throws IOException
{
final Buffer.PlainBuffer buf = new Buffer.PlainBuffer();
while ((serverID = readIdentification(buf)).isEmpty()) {
int b = connInfo.in.read();
if (b == -1)
throw new TransportException("Server closed connection during identification exchange");
buf.putByte((byte) b);
}
}
The thread never gets the control back, as the server never replies with its identity. Seems like the code is stuck in this While loop. No timeouts, or SSH exceptions are thrown, my client just keeps waiting forever, and the thread gets deadlocked.
This is the readIdentification method's impl:
private String readIdentification(Buffer.PlainBuffer buffer)
throws IOException {
String ident = new IdentificationStringParser(buffer, loggerFactory).parseIdentificationString();
if (ident.isEmpty()) {
return ident;
}
if (!ident.startsWith("SSH-2.0-") && !ident.startsWith("SSH-1.99-"))
throw new TransportException(DisconnectReason.PROTOCOL_VERSION_NOT_SUPPORTED,
"Server does not support SSHv2, identified as: " + ident);
return ident;
}
Seems like ConnectionInfo's inputstream never gets data to read, as if the server closed the connection (even if, as said earlier, no exception is thrown).
I've tried to simulate this error by saturating the negotiation, closing sockets while connecting, using conntrack to kill established connections while the handshake is being made, but with no luck at all, so any help would be HIGHLY appreciated.
: )
I bet following code creates a problem:
String ident = new IdentificationStringParser(buffer, loggerFactory).parseIdentificationString();
if (ident.isEmpty()) {
return ident;
}
If the IdentificationStringParser.parseIdentificationString() returns empty string, it will be returned to the caller method. The caller method will keep calling the while ((serverID = readIdentification(buf)).isEmpty()) since the string is always empty. The only way to break the loop would be if call to int b = connInfo.in.read(); returns -1... but if server keeps sending the data (or resending the data) this condition is never met.
If this is the case I would add some kind of artificial way to detect this like:
private String readIdentification(Buffer.PlainBuffer buffer, AtomicInteger numberOfAttempts)
throws IOException {
String ident = new IdentificationStringParser(buffer, loggerFactory).parseIdentificationString();
numberOfAttempts.incrementAndGet();
if (ident.isEmpty() && numberOfAttempts.intValue() < 1000) { // 1000
return ident;
} else if (numberOfAttempts.intValue() >= 1000) {
throw new TransportException("To many attempts to read the server ident").
}
if (!ident.startsWith("SSH-2.0-") && !ident.startsWith("SSH-1.99-"))
throw new TransportException(DisconnectReason.PROTOCOL_VERSION_NOT_SUPPORTED,
"Server does not support SSHv2, identified as: " + ident);
return ident;
}
This way you would at least confirm that this is the case and can dig further why .parseIdentificationString() returns empty string.
Faced a similar issue where we would see:
INFO [net.schmizz.sshj.transport.TransportImpl : pool-6-thread-2] - Client identity string: blablabla
INFO [net.schmizz.sshj.transport.TransportImpl : pool-6-thread-2] - Server identity string: blablabla
But on some occasions, there were no server response.
Our service would typically wake up and transfer several files simultaneously, one file per connection / thread.
The issue was in the sshd server config, we increased maxStartups from default value 10
(we noticed the problems started shortly after batch sizes increased to above 10)
Default in /etc/ssh/sshd_config:
MaxStartups 10:30:100
Changed to:
MaxStartups 30:30:100
MaxStartups
Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).
If you cannot control the server, you might have to find a way to limit your concurrent connection attempts in your client code instead.
I am using P4Java library in my build.gradle file to sync a large zip file (>200MB) residing at a remote Perforce repository but I am encountering a "java.net.SocketTimeoutException: Read timed out" error either during the sync process or (mostly) during deleting the temporary client created for the sync operation. I am referring http://razgulyaev.blogspot.in/2011/08/p4-java-api-how-to-work-with-temporary.html for working with temporary clients using P4Java API.
I tried increasing the socket read timeout from default 30 sec as suggested in http://answers.perforce.com/articles/KB/8044 and also by introducing sleep but both approaches didn't solved the problem. Probing the server to verify the connection using getServerInfo() right before performing sync or delete operations results in a successful connection check. Can someone please point me as to where I should look for answers?
Thank you.
Providing the code snippet:
void perforceSync(String srcPath, String destPath, String server) {
// Generating the file(s) to sync-up
String[] pathUnderDepot = [
srcPath + "*"
]
// Increasing timeout from default 30 sec to 60 sec
Properties defaultProps = new Properties()
defaultProps.put(PropertyDefs.PROG_NAME_KEY, "CustomBuildApp")
defaultProps.put(PropertyDefs.PROG_VERSION_KEY, "tv_1.0")
defaultProps.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, "60000")
// Instantiating the server
IOptionsServer p4Server = ServerFactory.getOptionsServer("p4java://" + server, defaultProps)
p4Server.connect()
// Authorizing
p4Server.setUserName("perforceUserName")
p4Server.login("perforcePassword")
// Just check if connected successfully
IServerInfo serverInfo = p4Server.getServerInfo()
println 'Server info: ' + serverInfo.getServerLicense()
// Creating new client
IClient tempClient = new Client()
// Setting up the name and the root folder
tempClient.setName("tempClient" + UUID.randomUUID().toString().replace("-", ""))
tempClient.setRoot(destPath)
tempClient.setServer(p4Server)
// Setting the client as the current one for the server
p4Server.setCurrentClient(tempClient)
// Creating Client View entry
ClientViewMapping tempMappingEntry = new ClientViewMapping()
// Setting up the mapping properties
tempMappingEntry.setLeft(srcPath + "...")
tempMappingEntry.setRight("//" + tempClient.getName() + "/...")
tempMappingEntry.setType(EntryType.INCLUDE)
// Creating Client view
ClientView tempClientView = new ClientView()
// Attaching client view entry to client view
tempClientView.addEntry(tempMappingEntry)
tempClient.setClientView(tempClientView)
// Registering the new client on the server
println p4Server.createClient(tempClient)
// Surrounding the underlying block with try as we want some action
// (namely client removing) to be performed in any way
try {
// Forming the FileSpec collection to be synced-up
List<IFileSpec> fileSpecsSet = FileSpecBuilder.makeFileSpecList(pathUnderDepot)
// Syncing up the client
println "Syncing..."
tempClient.sync(FileSpecBuilder.getValidFileSpecs(fileSpecsSet), true, false, false, false)
}
catch (Exception e) {
println "Sync failed. Trying again..."
sleep(60 * 1000)
tempClient.sync(FileSpecBuilder.getValidFileSpecs(fileSpecsSet), true, false, false, false)
}
finally {
println "Done syncing."
try {
p4Server.connect()
IServerInfo serverInfo2 = p4Server.getServerInfo()
println '\nServer info: ' + serverInfo2.getServerLicense()
// Removing the temporary client from the server
println p4Server.deleteClient(tempClient.getName(), false)
}
catch(Exception e) {
println 'Ignoring exception caught while deleting tempClient!'
/*sleep(60 * 1000)
p4Server.connect()
IServerInfo serverInfo3 = p4Server.getServerInfo()
println '\nServer info: ' + serverInfo3.getServerLicense()
sleep(60 * 1000)
println p4Server.deleteClient(tempClient.getName(), false)*/
}
}
}
One unusual thing which I observed while deleting tempClient was it was actually deleting the client but still throwing "java.net.SocketTimeoutException: Read timed out" which is why I ended up commenting the second delete attempt in the second catch block.
Which version of P4Java are you using? Have you tried this out with the newest P4Java? There are notable fixes dealing with RPC sockets since the 2013.2 version forward as can be seen in the release notes:
http://www.perforce.com/perforce/doc.current/user/p4javanotes.txt
Here are some variations that you can try where you have your code to increase timeout and instantiating the server:
a] Have you tried to passing props in its own argument,? For example:
Properties prop = new Properties();
prop.setProperty(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, "300000");
UsageOptions uop = new UsageOptions(prop);
server = ServerFactory.getOptionsServer(ServerFactory.DEFAULT_PROTOCOL_NAME + "://" + serverPort, prop, uop);
Or something like the following:
IOptionsServer p4Server = ServerFactory.getOptionsServer("p4java://" + server, defaultProps)
You can also set the timeout to "0" to give it no timeout.
b]
props.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, "60000");
props.put(RpcPropertyDefs.RPC_SOCKET_POOL_SIZE_NICK, "5");
c]
Properties props = System.getProperties();
props.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, "60000");
IOptionsServer server =
ServerFactory.getOptionsServer("p4java://perforce:1666", props, null);
d] In case you have Eclipse users using our P4Eclipse plugin, the property can be set in the plugin preferences (Team->Perforce->Advanced) under the Custom P4Java Properties.
"sockSoTimeout" : "3000000"
REFERENCES
Class RpcPropertyDefs
http://perforce.com/perforce/doc.current/manuals/p4java-javadoc/com/perforce/p4java/impl/mapbased/rpc/RpcPropertyDefs.html
P4Eclipse or P4Java: SocketTimeoutException: Read timed out
http://answers.perforce.com/articles/KB/8044
I have rabbitmq setup on my machine and it has 3 different queues. One java code is listening to a queue and other queues are sending messages to python codes. Now python codes are working fine but java code seems to have a problem with AMQ. Following error is coming:
Exception in thread "main" com.rabbitmq.client.PossibleAuthenticationFailureException: Possibly caused by authentication failure
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:341)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:590)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
at com.elki.test.Worker.main(Worker.java:73)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:343)
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:216)
at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:202)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:326)
... 3 more
Caused by: java.io.EOFException
at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:95)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:139)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:532)
at java.lang.Thread.run(Thread.java:744)
How come there could be an AuthenticationFailure with java but not with python.
Any help appreciated.
CODE:
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
com.rabbitmq.client.Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
"do some work"
System.out.println(" [x] Done" );
int prefetchCount = 1;
channel.basicQos(prefetchCount);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
I suspect it's because you haven't set the password nor the username on the ConnectionFactory object, and so it can't authenticate with RabbitMQ. (Perhaps your Python code is passing those in, and so therefore can authenticate.)
Try adding this code before calling factory.newConnection:
factory.setUsername(userName);
factory.setPassword(password);
replacing userName and password as needed for your code.
I had same error. The problem was that the rabbitmq was started with default config on ipv6 protocol. I don't know why, but it does not work on windows linux subsystem.
Force ipv4 helped for me:
cat /etc/rabbitmq/rabbitmq.config
[
{rabbit, [
{tcp_listeners, [{"127.0.0.1", 5672}]}
]}
].
By default rabbitmq uses ipv6 address ::1.
PS^ You need to create config file if there are not exists.