How to get consumerTag in spring-rabbitmq 1.x - spring-amqp

the spring-rabbitmq config is like
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.1.3.RELEASE</version>
I want to canceling a consumer , use channel.basicCannel(consumerTag)
when i use ChannelAwareMessageListener in spring-rabbitmq 2.x version, consumerTag are
in MessageProperties,
but my online service is use 1.x version, there has no consumerTag in MessageProperties,
so i cant use the basicCancel api
my full listener code below
public class RPCListener implements ChannelAwareMessageListener {
private static final Logger log = LoggerFactory.getLogger(RPCListener.class);
#Autowired
private MessagePropertiesConverter messagePropertiesConverter;
private MessageConverter messageConverter = new SimpleMessageConverter();
#Autowired
private AmqpTemplate amqpTemplate;
private Boolean flag = false;
#Override
public void onMessage(Message message, Channel channel) throws Exception {
try {
log.error("DeliveryTag(): {}", message.getMessageProperties().getDeliveryTag());
if (flag) {
log.error("canceling....");
//If true, messages will be requeued and possibly
channel.basicRecover(true);
// there is no consumerTag property in MessageProperties
//channel.basicCancel(message.getMessageProperties().getConsumerTag());
return;
}
amqpTemplate.send(message.getMessageProperties().getReplyTo(), message);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
e.printStackTrace();
}
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
}
Is there any way to get consumerTag?
Thanks all!

1.1.3 is 7 years old; the consumerTag was added to MessageProperties in 1.4.2.
The only supported 1.x version is 1.7.14 - see the project page.
1.7.x will no longer be supported after this year.
However; you should NOT manually cancel the consumer; stop the container instead.

Related

Events stuck durin processing in Java app +Srping Amqp

After addded concurrrency to the #RabbitListened faced with problem that sometimes events are stuck in app.
When restarting app it's continue works normally. But then could aslo stuck suddenly after sometime.
#RabbitListener(
queues = "${app.queue}",
ackMode = "MANUAL",
concurrency = 2-5,
messageConverter = "jsonMessageConverter")
public void consumeEvent(AppEvent event, Channel channel, #Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
try {
.....
doAck(channel, deliveryTag);
} catch (Throwable e) {
.....
doNack(channel, deliveryTag);
}
}
#Bean
public PooledChannelConnectionFactory connectionFactory(){
ConnectionFactory rabbitConnectionFactory = new ConnectionFactory();
rabbitConnectionFactory.setHost(host);
rabbitConnectionFactory.setPort(port);
rabbitConnectionFactory.setUsername(userName);
rabbitConnectionFactory.setPassword(password);
return new PooledChannelConnectionFactory(rabbitConnectionFactory);
}
#Bean
public RabbitTemplate rabbitTemplate(){
final var rabbitTemplate = new RabbitTemplate(connectionFactory());
rabbitTemplate.setMessageConverter(getJsonMessageConverter());
return rabbitTemplate;
}
#Bean("jsonMessageConverter")
public Jackson2JsonMessageConverter getJsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
In thread dump there are 3 threads like on picture

How to configure Micronaut and Micrometer to write ILP directly to InfluxDB?

I have a Micronaut application that uses Micrometer to report metrics to InfluxDB with the micronaut-micrometer project. Currently it is using the Statsd Registry provided via the io.micronaut.configuration:micronaut-micrometer-registry-statsd dependency.
I would like to instead output metrics in Influx Line Protocol (ILP), but the micronaut-micrometer project does not offer an Influx Registry currently. I tried to work around this by importing the io.micrometer:micrometer-registry-influx dependency and configuring an InfluxMeterRegistry manually like this:
#Factory
public class MyMetricRegistryConfigurer implements MeterRegistryConfigurer {
#Bean
#Primary
#Singleton
public MeterRegistry getMeterRegistry() {
InfluxConfig config = new InfluxConfig() {
#Override
public Duration step() {
return Duration.ofSeconds(10);
}
#Override
public String db() {
return "metrics";
}
#Override
public String get(String k) {
return null; // accept the rest of the defaults
}
};
return new InfluxMeterRegistry(config, Clock.SYSTEM);
}
#Override
public boolean supports(MeterRegistry meterRegistry) {
return meterRegistry instanceof InfluxMeterRegistry;
}
}
When the application runs, the metrics are exposed on my /metrics endpoint as I would expect, but nothing gets written to InfluxDB. I confirmed that my local InfluxDB accepts metrics at the expected localhost:8086/write?db=metrics endpoint using curl. Can anyone give me some pointers to get this working? I'm wondering if I need to manually define a reporter somewhere...
After playing around for a bit, I got this working with the following code:
#Factory
public class InfluxMeterRegistryFactory {
#Bean
#Singleton
#Requires(property = MeterRegistryFactory.MICRONAUT_METRICS_ENABLED, value =
StringUtils.TRUE, defaultValue = StringUtils.TRUE)
#Requires(beans = CompositeMeterRegistry.class)
public InfluxMeterRegistry getMeterRegistry() {
InfluxConfig config = new InfluxConfig() {
#Override
public Duration step() {
return Duration.ofSeconds(10);
}
#Override
public String db() {
return "metrics";
}
#Override
public String get(String k) {
return null; // accept the rest of the defaults
}
};
return new InfluxMeterRegistry(config, Clock.SYSTEM);
}
}
I also noticed that an InfluxMeterRegistry will be available out of the box in the future for micronaut-micrometer as of v1.2.0.

Codenameone Enum.valueof String throws IllegalArgument exception on iOS 9

In codenameone, when using valueOf(String s) on enum throws IllegalArgument exception: No enum const on iPhone5, iOS9, but works fine on simulator and Android. It worked fine 3-4 weeks ago. Type OK in the text box and press the button, on simulator fine, if you build it and run it for iOS9 - you will get the exception.
Bellow a snapshot code to test:
public class MyApplication {
private Form current;
private Resources theme;
enum popo { OK, ERROR,EXCEPTION};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World");
hi.setLayout(new BorderLayout());
final TextArea input = new TextArea();
Button testr = new Button("Touch me");
testr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
popo q = popo.valueOf(input.getText());
Dialog.show("title",
"just found string = "+input.getText()+" \nthat gives enum = "+q.toString()
, "OK", null);
}
});
hi.addComponent(BorderLayout.CENTER, input);
hi.addComponent(BorderLayout.SOUTH,testr);
hi.show();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}
Many thanks,
Goran.
Enum's values() and related calls aren't implemented in Codename One. The crux of the issue is that they fail during obfuscation (for Android) and require some reflection code generated by the javac tool.
The workaround is to use something like this:
enum popo {OK("OK"), ERROR("ERROR),EXCEPTION("EXCEPTION");
public popo(String value) {
this.value = value;
}
String value;
};
Then use myPopo.value.

Custom JavaFX WebView Protocol Handler

I am trying to write my own protocol handler for a JavaFX application that uses webview to access a single website. What I have done so far
My custom URLStreamHandlerFactory
public class MyURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
System.out.println("Protocol: " + protocol);
if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) {
return new MyURLStreamHandler();
} else {
return new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return new URLConnection(u) {
#Override
public void connect() throws IOException {
}
};
}
};
}
}
}
My custom URLStreamHandler
public class MyURLStreamHandler extends java.net.URLStreamHandler{
protected HttpURLConnection openConnection(URL u){
MyURLConnection q = new MyURLConnection(u);
return q;
}
}
My custom HttpURLConnection
public class MyURLConnection extends HttpURLConnection {
static int defaultPort = 443;
InputStream in;
OutputStream out;
Socket s;
publicMyURLConnection(URL url) {
super(url);
try {
setRequestMethod("POST");
} catch (ProtocolException ex) {
ex.printStackTrace();
}
}
public void setRequestProperty(String name, String value){
super.setRequestProperty(name, value);
System.out.println("Namee: " + name);
System.out.println("Value: " + value);
}
public String getRequestProperty(String name){
System.out.println("GET REQUEST: ");
return super.getRequestProperty(name);
}
public OutputStream getOutputStream() throws IOException {
OutputStream os = super.getOutputStream();
System.out.println("Output: " + os);
return os;
}
public InputStream getInputStream() throws IOException {
InputStream is = super.getInputStream();
System.out.println("INout stream: " + is);
return is;
}
#Override
public void connect() throws IOException {
}
#Override
public void disconnect() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean usingProxy() {
throw new UnsupportedOperationException("Not supported yet.");
}
When I run the application I get the following error althouhg it seems to set some headers
Jul 08, 2013 11:09:04 AM com.sun.webpane.webkit.network.URLLoader doRun
WARNING: Unexpected error
java.net.UnknownServiceException: protocol doesn't support input
at java.net.URLConnection.getInputStream(URLConnection.java:839)
at qmed.QMedURLConnection.getInputStream(MyURLConnection.java:67)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at com.sun.webpane.webkit.network.URLLoader.receiveResponse(URLLoader.java:383)
at com.sun.webpane.webkit.network.URLLoader.doRun(URLLoader.java:142)
at com.sun.webpane.webkit.network.URLLoader.access$000(URLLoader.java:44)
at com.sun.webpane.webkit.network.URLLoader$1.run(URLLoader.java:106)
at com.sun.webpane.webkit.network.URLLoader$1.run(URLLoader.java:103)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.webpane.webkit.network.URLLoader.run(URLLoader.java:103)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
All I want to do is get the response back for a given request and reads its binary data. I want the protocol to behave exactly the same way as the default one and only check the binary data of a given respone. What am I doing wrong?
The application is doing all shorts of URLConnections. Is it correct to use a HTTPURLConnection as my custom URLConnection class when the protocol is http or https and start a default URLStreamHandler when other protocols are used like I am doing in MyURLStreamHandlerFactory? Should I just extend the default URLConnection class in MYURLConnection to handle all protocols the same?
Any help would be much appreciated as this is a project threatening problem
Thank you
It might be that all you are missing is a setDoInput(true) or override getDoInput() and return true (that's what i did).
If that does not help check out my working solution:
MyURLStreamHandlerFactory:
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
public class MyURLStreamHandlerFactory implements URLStreamHandlerFactory
{
public URLStreamHandler createURLStreamHandler(String protocol)
{
if (protocol.equals("myapp"))
{
return new MyURLHandler();
}
return null;
}
}
Register Factory:
URL.setURLStreamHandlerFactory(new MyURLStreamHandlerFactory());
MyURLHandler :
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class MyURLHandler extends URLStreamHandler
{
#Override
protected URLConnection openConnection(URL url) throws IOException
{
return new MyURLConnection(url);
}
}
MyURLConnection:
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
/**
* Register a protocol handler for URLs like this: <code>myapp:///pics/sland.gif</code><br>
*/
public class MyURLConnection extends URLConnection
{
private byte[] data;
#Override
public void connect() throws IOException
{
if (connected)
{
return;
}
loadImage();
connected = true;
}
public String getHeaderField(String name)
{
if ("Content-Type".equalsIgnoreCase(name))
{
return getContentType();
}
else if ("Content-Length".equalsIgnoreCase(name))
{
return "" + getContentLength();
}
return null;
}
public String getContentType()
{
String fileName = getURL().getFile();
String ext = fileName.substring(fileName.lastIndexOf('.'));
return "image/" + ext; // TODO: switch based on file-type
}
public int getContentLength()
{
return data.length;
}
public long getContentLengthLong()
{
return data.length;
}
public boolean getDoInput()
{
return true;
}
public InputStream getInputStream() throws IOException
{
connect();
return new ByteArrayInputStream(data);
}
private void loadImage() throws IOException
{
if (data != null)
{
return;
}
try
{
int timeout = this.getConnectTimeout();
long start = System.currentTimeMillis();
URL url = getURL();
String imgPath = url.toExternalForm();
imgPath = imgPath.startsWith("myapp://") ? imgPath.substring("myapp://".length()) : imgPath.substring("myapp:".length()); // attention: triple '/' is reduced to a single '/'
// this is my own asynchronous image implementation
// instead of this part (including the following loop) you could do your own (synchronous) loading logic
MyImage img = MyApp.getImage(imgPath);
do
{
if (img.isFailed())
{
throw new IOException("Could not load image: " + getURL());
}
else if (!img.hasData())
{
long now = System.currentTimeMillis();
if (now - start > timeout)
{
throw new SocketTimeoutException();
}
Thread.sleep(100);
}
} while (!img.hasData());
data = img.getData();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public OutputStream getOutputStream() throws IOException
{
// this might be unnecessary - the whole method can probably be omitted for our purposes
return new ByteArrayOutputStream();
}
public java.security.Permission getPermission() throws IOException
{
return null; // we need no permissions to access this URL
}
}
Some parts of MyURLConnection might not be necessary for it to work, but like this it works for me.
Usage in JavaFX WebView:
<img src="myapp:///pics/image.png"/>
Note about permissions:
I used an applet with AllPermissions for my test with the above code.
In a Sandbox-Applet this won't work, as the setFactory permission is missing.
This is not directly related to the question asked, but might make the question itself obsolete.
With Java SE 6 Update 10 Java Applets support to access resources on any domain and port which is correctly set up with a crossdomain.xml.
With this the reason to register your own protocol might become obsolete, as you can access all resources that you need.
Another idea is: If you are trying to create a kind of network sniffer, why not directly use a network sniffer/analyzer program designed for such a task?
By activating Logging and Tracing in the Java Control-Panel your Java-Console will print all attempts and executed network calls including those from the WebView.
You can see all HTTP & HTTPS calls and their return-code + cookie data.
You might also see other protocol connections, but probably not any data sent over them.
This applies to Applets in a Browser.
If you need this in a different context maybe there is a way to activate the same options by passing command line parameters.

Tried to read incoming SMS content but getting Error in Blackberry

Hi friends i am trying to read incoming sms but getting warning like this . Invocation of questionable method: java.lang.String.(String) found in: mypackage.MyApp$ListeningThread.run()
Here is my code is
public class MyApp extends UiApplication {
//private ListeningThread listener;
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
invokeAndWait(new Runnable() {
public void run() {
ListeningThread listener = new ListeningThread();
listener.start();
}
});
pushScreen(new MyScreen());
}
private static class ListeningThread extends Thread {
private boolean _stop = false;
private DatagramConnection _dc;
public synchronized void stop() {
_stop = true;
try {
_dc.close(); // Close the connection so the thread returns.
} catch (IOException e) {
System.err.println(e.toString());
}
}
public void run() {
try {
_dc = (DatagramConnection) Connector.open("sms://");
for (;;) {
if (_stop) {
return;
}
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
String address = new String(d.getAddress());
String msg = new String(d.getData());
if(msg.startsWith("START")){
Dialog.alert("hello");
}
System.out.println("Message received: " + msg);
System.out.println("From: " + address);
System.exit(0);
}
} catch (IOException e) {
System.err.println(e.toString());
}
}
}
}
Please correct me where i am wrong.Is possible give me some code to read incoming sms content in blackberry.
A few points about your code:
That invokeAndWait call to launch a thread makes no sense. It doesn't harm, but is kind of waste. Use that method only to perform UI related operations.
You should try using "sms://:0" as param for Connector.open. According to the docs, a parameter with the form {protocol}://[{host}]:[{port}] will open the connection in client mode (which makes sense, since you are on the receiving part), whereas not including the host part will open it in server mode.
Finally, if you can't get it working, you could use instead the third method specified in this tutorial, which you probably have already read.
The error you quoted is complaining about the use of the String constructor that takes a string argument. Since strings are immutable in Java-ME, this is just a waste. You can use the argument string directly:
Invocation of questionable method: java.lang.String.(String) found in: mypackage.MyApp$ListeningThread.run()
//String address = new String(d.getAddress());
String address = d.getAddress();
// getData() returns a byte[], so this is a different constructor
// However, this leaves the character encoding unspecified, so it
// will default to cp1252, which may not be what you want
String msg = new String(d.getData());

Resources