dave83
dave83
Reputation Top 1%
David Lee
10 Snippets  (91st place)
Published
0 Channels
Created
8 Channels
Following
354 points  (86th place)
Reputation
Junior Code Generator
Serious Code Generator
Junior Publisher
Serious Publisher
Junior Judge
Serious Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Famous Coder
Serious Famous Coder
Junior Wise Coder
Senior Popular Coder
Serious Famous Coder

Recent Snippets See all snippets by dave83

public by dave83  223898  8  7  0

How to run methods in class marked with specific Java annotation

The snippet shows how to invoke only methods of a class marked with specific annotation. The list of methods class (MyTest) is returned using reflection. Annotations are returned via getAnnotation() method. The method is executed via invoke() method.
import java.lang.reflect.Method;

public class MyTest {

    @MyAnnotation
    public void method1() {
      System.out.println("method1");
    }

    public void method2() {
      System.out.println("method2");
    }
    
    @MyAnnotation
    public void method3() {
      System.out.println("method3");
    }
    
    public static void main(String[] args) {

        MyTest runner = new MyTest();
        Method[] methods = runner.getClass().getMethods();

        for (Method method : methods) {
            MyAnnotation annos = method.getAnnotation(MyAnnotation.class);
            if (annos != null) {
                try {
                    method.invoke(runner);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
} 
                        
;

public by dave83  2751  1  6  2

How to send messages using MessageProducer in JMS

The code shows how to send messages using a MessageProducer in Java Message Service. Destination object is the queue where to send, read as JNDI lookup queue. The Session used is not transactional and auto acknowledged. Note the delivery mode of send method is set to Persistent, so the message will be persisted by JMS broker and its delivery wil
// Load JNDI properties
Properties properties = new Properties();            
properties.load(this.getClass().getResourceAsStream("my.properties"));

//Create the initial context       
Context ctx = new InitialContext(properties);
		            
// look up destination and connection factory
Destination destination = (Destination)ctx.lookup("myQueue");
ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("Connectionfactory");
Connection connection = conFac.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(destination);
TextMessage message;

// Send a series of messages in a loop
for (int i = 1; i < 100; i++)
{
    message = session.createTextMessage("Message " + i);
    messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);             
}
;

public by dave83  3040  1  7  4

Reading Messages from a Queue with a MessageConsumer in JMS

The code shows how to read messages from a queue using a Message Consumer in java Java Message Service. MessageConsumer object is created from the Session object, defined as non-transacted and auto-acknowledged, invoking createConsumer method. Such method will bind the consumer to the queue defined via JNDI lookup table.
//Creating a non-transacted, auto-acknowledged session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//Creating messageConsumer bound to destination queue
MessageConsumer messageConsumer = session.createConsumer(destination);
connection.start();
		
Message message;
boolean end = false;
//read
while (!end)
{
    message = messageConsumer.receive();
    String text;
    if (message instanceof TextMessage)
    {
        text = ((TextMessage) message).getText();
    }
    else
    {
        byte[] body = new byte[(int) ((BytesMessage) message).getBodyLength()];
        ((BytesMessage) message).readBytes(body);
        text = new String(body);
    }
    if (text.equals("EXIT"))
    {
        System.out.println("Received exit message " + text);
        end = true;
    }
    else
    {
        System.out.println("Received  message:  " + text);
    }
}
//Tear down connection
connection.close();
;

public by dave83  2682  1  7  4

How to create an asynchronous MessageListener in JMS

This code is an example of Java Message Service message listener implementation. It shows how to create an asynchronous MessageListener, in order to receive message asynchronously as they are delivered to the message consumer. The client needs to create a message listener that implements the MessageListener interface. The MessageListener is as
//Import the JMS API classes.
import javax.jms.*;

public class HelloWorldMessage implements MessageListener {
	public void onMessage(Message message) {
		/* Unpack and handle the messages received */
		String newStockData = null;
		/* Unpack and handle the messages received */
		try {
			newStockData = ((TextMessage) message).getText();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (newStockData != null) {
			/* Logic related to the data */
		}
	}
}
;

public by dave83  2721  0  6  3

JAX-RS web service using Path annotation

This simple code shows how to implement a JAX-RS rest web service. @Path annotation is used to bind URI pattern to a specific method. The web service path '/path' is the main root. On a GET request to URI '/path' the method getUser() will be invoked. On a GET request to URI '/path/test' the method getTest() will be invoked. In this simple j
import javax.ws.*;
 
@Path("/path")
public class WebRestService {
 
	@GET
	public Response getUser() {
 
		return Response.status(200).entity("get User is called").build();
 
	}
 
	@GET
	@Path("/test")
	public Response getTest() {
 
		return Response.status(200).entity("get Test is called").build();
 
	}
}
;