Error is occurred while pushing the Message in IBM MQ Lite - java

I am using IBM MQ Light.
I am trying to push a message in IBM MQ Lite through java program, My Connection is well and good. When i run the program and check the Localhost it shows me that client is connected but after 3-4 seconds it is disconnected and Exception is thrown at console.
Following is my error log:
Problem with subscribe request: amqp:unauthorized-access: AMQXR0042E: A subscribe request was not authorized for channel PlainText received from 127.0.0.1. AMQXR0004E: MQSeries verb=SPISubscribe(String) returned cc=2(int) MQCC_FAILED rc=2035(int) MQRC_NOT_AUTHORIZED

A 2035 error code means you are not authorized. You may need to get more info to determine why your client is failing. You could use the MQS_REPORT_NOAUTH or MQSAUTHERRORS setting to get more info about the authority failure and what access is failing.

I have a sample code by which you can push the message in IBM MQ Lite
package com.Queue;
import com.ibm.mqlight.api.ClientOptions;
import com.ibm.mqlight.api.Delivery;
import com.ibm.mqlight.api.DestinationAdapter;
import com.ibm.mqlight.api.NonBlockingClient;
import com.ibm.mqlight.api.NonBlockingClientAdapter;
import com.ibm.mqlight.api.StringDelivery;
public class SendReceive2
{
public static void main(String[] cmdline)
{
ClientOptions clientOpts = ClientOptions.builder().setCredentials("ad", "jms123").build();
NonBlockingClient.create("amqp://localhost", clientOpts, new NonBlockingClientAdapter<Void>()
{
public void onStarted(NonBlockingClient client, Void context)
{
client.subscribe("JmsQueue", new DestinationAdapter<Void>()
{
public void onMessage(NonBlockingClient client, Void context, Delivery delivery)
{
if (delivery.getType() == Delivery.Type.STRING)
System.out.println(((StringDelivery)delivery).getData());
}
}, null, null);
}
}, null);
NonBlockingClient.create("amqp://localhost", clientOpts, new NonBlockingClientAdapter<Void>()
{
public void onStarted(NonBlockingClient client, Void context)
{
client.send("JmsQueue", "Jms Queue is Formed!", null);
}
}, null);
}//main
}//class
Try it ,
It works in my case

Related

not able to connect the GCP RabbitMQ from java code Getting Connection Exception [duplicate]

I have used RMI in my code :
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1,double d2) throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {
public AddServerImpl() throws RemoteException {
}
public double add(double d1,double d2) throws RemoteException {
return d1+d2;
}
}
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String args[]) {
try {
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
} catch(Exception exc) {
System.out.println(exc);
}
}
}
import java.rmi.*;
public class AddClient {
public static void main(String args[]) {
try {
String Url="rmi://"+args[0]+"/AddServer";
AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(Url);
System.out.println("The first number is "+args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is: "+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("The Sum is: "+addServerIntf.add(d1,d2));
} catch(Exception exc) {
System.out.println(exc);
}
}
}
These are 4 .java files written.
Next i compile all these files.Then I create a stub using rmic AddServerImpl. After that i start rmi registry on server side using start rmiregistry. Then i start server using java AddServer and finally client using java AddClient 27.60.200.80 5 9.
But nothing happens
Exception that is thrown on client side is java.net.ConnectException : connection timed out : connect
What is the reason and how can i solve this?
On client machine these are the following .class files AddClient.class AddServerImpl.class AddServerImpl_Stub.class and on server side AddServer.class AddServerImpl.class AddServerImpl_Stub.class AddServerIntf.class
The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:
a) The IP/domain or port is incorrect
b) The IP/domain or port (i.e service) is down
c) The IP/domain is taking longer than your default timeout to respond
d) You have a firewall that is blocking requests or responses on whatever port you are using
e) You have a firewall that is blocking requests to that particular host
f) Your internet access is down
Note that firewalls and port or IP blocking may be in place by your ISP
Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a.
C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name.
Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.
Exception : java.net.ConnectException
This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:
Too many requests overloading the server
Request packet loss because of wrong network configuration or line overload
Sometimes firewall consume request packet before sever getting
Also depends on thread connection pool configuration and current status of connection pool
Response packet lost during transition
If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:
NSLOOKUP fabrikam.com
Test-NetConnection <IP returned from NSLOOKUP> -port 389

Java create/overwrite http server

I'm creating a plugin on a certain platform (the details are irrelevant) and need to create a HTTP endpoint. In normal circumstances you'd create a http server and stop it whenever you're done using it or when the application stops, however, in my case I can't detect when the plugin is being uninstalled/reinstalled.
The problem
When someone installs my plugin twice, the second time it will throw an error because I'm trying to create a http server on a port which is already in use. Since it's being reinstalled, I can't save the http server on some static variable either. In other words, I need to be able to stop a previously created http server without having any reference to it.
My attempt
I figured the only way to interact with the original reference to the http server would be to create a thread whenever the http server starts, and then overwrite the interrupt() method to stop the server, but somehow I'm still receiving the 'port is already in use' error. I'm using Undertow as my http server library, but this problem applies to any http server implementation.
import io.undertow.Undertow;
import io.undertow.util.Headers;
public class SomeServlet extends Thread {
private static final String THREAD_NAME = "some-servlet-container-5391301";
private static final int PORT = 5839;
private Undertow server;
public static void listen() { // this method is called whenever my plugin is installed
deleteExistingServer();
new SomeServlet().start();
}
private static void deleteExistingServer() {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(THREAD_NAME)) {
t.interrupt();
}
}
}
#Override
public void run() {
createServer();
}
#Override
public void interrupt() {
try {
System.out.println("INTERRUPT");
this.server.stop();
} finally {
super.interrupt();
}
}
private void createServer() {
this.server = Undertow.builder()
.addHttpListener(PORT, "localhost")
.setHandler(exchange -> {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World!");
})
.build();
this.server.start();
}
}
Desired behaviour
Whenever listen() is called, it will remove any previously existing http server and create a new one, without relying on storing the server on a static variable.
You could try com.sun.net.httpserver.HttpServer. Use http://localhost:8765/stop to stop and 'http://localhost:8765/test' for test request:
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class TestHttpServer {
public static void main(String[] args) throws IOException {
final HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(8765), 0);
server.createContext("/test", httpExchange -> {
String response = "<html>TEST!!!</html>";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
});
server.createContext("/stop", httpExchange -> server.stop(1));
server.start();
}
}

httpClient connection not closing

Version
vert.x core: 3.3.0
Context
Am just trying to run http client in core examples io.vertx.example.core.http.simple.Client.
While running this example its found that the established connection not closing after completion of request.
Server side I didnt see any issue. Since while trying with jmeter and server its working fine. So I think that the problem is in the HttpClient.
Anyone can help me on this?
Thanks in advance.
Steps to reproduce
running io.vertx.example.core.http.simple.Server code
running io.vertx.example.core.http.simple.Client code
Extra
The following shown even after the request and response is ended. while giving
LINUX
lsof -i -P
java 32551 USER 223u IPv4 16264097 0t0 TCP localhost:8080->localhost:26980 (ESTABLISHED)
java 32634 USER 218u IPv4 16264087 0t0 TCP localhost:26980->localhost:8080 (ESTABLISHED)
WINDOWS
TCP 127.0.0.1:8080 FSSCHND12957:56893 ESTABLISHED
TCP 127.0.0.1:56893 FSSCHND12957:8080 ESTABLISHED
Tried in both LINUX and WINDOWS system.
Client Code
package io.vertx.example.core.http.simple;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
#author Tim Fox
*/
public class Client extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Client.class);
}
#Override
public void start() throws Exception {
vertx.createHttpClient().getNow(8080, "localhost", "/", resp -> {
System.out.println("Got response " + resp.statusCode());
resp.bodyHandler(body -> {
System.out.println("Got data " + body.toString("ISO-8859-1"));
});
});
}
}
Server Code
package io.vertx.example.core.http.simple;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
#author Tim Fox
*/
public class Server extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Server.class);
}
#Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(req -> {
req.response().putHeader("content-type", "text/html").end("
Hello from vert.x!
");
}).listen(8080);
}
}
We have to close the httpClient which we normally do in java. Only end() is not closing the connection. httpClient.close() is required.... This solved my issue..
Modified code:
public class Client extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Client.class);
}
#Override
public void start() throws Exception {
HttpClient httpClient = vertx.createHttpClient().getNow(8080, "localhost", "/", resp -> {
System.out.println("Got response " + resp.statusCode());
resp.bodyHandler(body -> {
System.out.println("Got data " + body.toString("ISO-8859-1"));
httpClient.close();
});
});
}
}

Low disk space causes RabbitMQ to loose messages instead of blocking the connection

I have a java application that publishes messages to a RabbitMQ server.
When the available disk space drops below rabbit's low watermark I get unexpected behavior.
The expected behavior is that the connection will become blocking, making my application hang on the call to Channel.basicPublish.
The actual behavior is that the connection appears to be blocking in the management console, but calls to Channel.basicPublish return with no errors and the messages that were supposed to be published are lost.
This behavior undermines the most important feature of RabbitMQ, which is robustness.
Below is a minimal version of my application for testing. All it does is publish a message every second with an incrementing index (1, 2, 3, ...). The messages are received just fine by the RabbitMQ server, until I set the low watermark to a very high value, by putting the following line in the rabbitmq.config file:
[
{rabbit, [{disk_free_limit, 60000000000}]}
].
After restarting the server, I get a low disk space notification in the management console, the connection is marked as 'blocking', and no more messages are received by the server. However, the application keeps running and sending messages as if nothing is wrong. When I reduce the watermark back to a normal value messages are received by the server again, but all the messages that were sent while the connection was blocking are lost.
Am I doing something wrong?
Is this a bug in RabbitMQ?
If so, is there a workaround?
OS: Windows 8 64bit
RabbitMQ server version: 3.1.1
RabbitMQ Java client version: 3.1.0
Test application code:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
private final static String QUEUE_NAME = "testQueue";
private static Channel channel = null;
private static void connectToRabbitMQ() throws IOException {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(
QUEUE_NAME,
true, // Durable - survive a server restart
false, // Not exclusive to this connection
false, // Do not autodelete when no longer in use
null // Arguments
);
}
private static void disposeChannel()
{
if (channel == null) {
return;
}
try {
channel.close();
} catch (Exception e) {
} finally {
channel = null;
}
}
public static void main(String[] args) throws Exception {
boolean interrupted = false;
int messageNumber = 1;
while (!interrupted) {
byte[] message = Integer.toString(messageNumber).getBytes();
try {
if (channel == null) {
connectToRabbitMQ();
}
channel.basicPublish(
"",
QUEUE_NAME,
MessageProperties.MINIMAL_PERSISTENT_BASIC,
message
);
logger.info("Published message number {}", messageNumber);
messageNumber++;
} catch (Exception e) {
logger.info("Unable to connect to RabbitMQ...");
disposeChannel();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.info("Interrupted");
interrupted = true;
}
}
}
}

Simple Remote Shared Object with Red5 Flash Server

I am trying to create a simple chat client using the red5 media server, but I seem to be having a slight hiccup. I am creating a shared object on the server side, and it seems to be creating it successfully. However, when I make changes to the object via the client (type a message), the SYNC event fires, but the content within the shared object remains empty. I suspect I am doing something wrong on the java end, any advice?
Console Results:
Success!
Server Message: clear
Server Message: [object Object]
Local message: asdf
Server Message: change
Server Message: [object Object]
Local message: fdsa
Server Message: change
Server Message: [object Object]
Local message: fewa
Server Message: change
Server Message: [object Object]
Server Side:
package org.red5.core;
import java.util.List;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.service.ServiceUtils;
import org.red5.server.api.so.ISharedObject;
// import org.apache.commons.logging.Log;
// import org.apache.commons.logging.LogFactory;
public class Application extends ApplicationAdapter {
private IScope appScope;
// private static final Log log = LogFactory.getLog( Application.class );
/** {#inheritDoc} */
#Override
public boolean connect(IConnection conn, IScope scope, Object[] params) {
appScope = scope;
createSharedObject(appScope, "generalChat", false); // Creates general chat shared object
return true;
}
/** {#inheritDoc} */
#Override
public void disconnect(IConnection conn, IScope scope) {
super.disconnect(conn, scope);
}
public void updateChat(Object[] params)
{
ISharedObject so = getSharedObject(appScope, "generalChat"); // Declares and stores general chat data in general chat shared object
so.setAttribute("point", params[0].toString());
}
}
Client Side:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
// This class is going to handle all data to and from from media server
public class SOConnect extends MovieClip
{
// Variables
var nc:NetConnection = null;
var so:SharedObject;
public function SOConnect():void
{
}
public function connect():void
{
// Create a NetConnection and connect to red5
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmp://localhost/testChat");
// Create a StoredObject for general chat
so = SharedObject.getRemote("generalChat", nc.uri, false);
so.connect(nc);
so.addEventListener(SyncEvent.SYNC, receiveChat)
}
public function sendChat(msg:String)
{
trace ("Local message: " + msg);
nc.call("updateChat", null, msg)
}
public function receiveChat(e:SyncEvent):void
{
for (var i in e.changeList)
{
trace ("Server Message: " + e.changeList[i].code)
trace ("Server Message: " + e.changeList[i])
}
}
// Given result, determine successful connection
private function netStatusHandler(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Success!");
}
else
{
trace("Failure!\n");
trace(e.info.code);
}
}
}
}
you don't need to write anything on the server side in order to do a chat in as3 and red5;
here is an example for you the chat that it is working and it is written in as3/flex3
Yes its posible to create a chat without writing server side code but i dont see how someone could control users disconnections or use lists of users on sync, anyway back to the subject maybe you have a problem with dir permissions so try running red5 as root/admin once , just to check if it works, if it does you should create a user (with the correct writing permissions) in your system and then run red5 using that user.

Categories