working on it ...


Explore Public Snippets

Sort by

Found 10 snippets

    public by dave83  223941  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 {
        public void method1() {
        public void method2() {
        public void 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 {
                    } catch (Exception e) {

    public by dave83  2885  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();            
    //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  3072  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);
    Message message;
    boolean end = false;
    while (!end)
        message = messageConsumer.receive();
        String text;
        if (message instanceof TextMessage)
            text = ((TextMessage) message).getText();
            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;
            System.out.println("Received  message:  " + text);
    //Tear down connection

    public by dave83  2725  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
    		if (newStockData != null) {
    			/* Logic related to the data */

    public by dave83  2756  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
    public class WebRestService {
    	public Response getUser() {
    		return Response.status(200).entity("get User is called").build();
    	public Response getTest() {
    		return Response.status(200).entity("get Test is called").build();

    public by dave83  4107  10  8  6

    HMTL pie chart using Google API

    This HTML and Javascript code shows how to render a simple pie chart using Google API Chart. The pie will show the percentage of items listed in var data, where you can bind an array as datasource of the chart. Each item will be displayed as a slice of pie. Option title will be rendered on top left.
        <script type="text/javascript" src=""></script>
        <script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Task', 'Election Day'],
              ['Candidate ABC', 21],
              ['Candidate DEF', 31],
              ['Candidate YXZ', 23],
              ['Candidate FOO', 10],
              ['Candidate BAR', 15]
            var options = {
              title: 'Exit polls'
            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            chart.draw(data, options);
        <div id="piechart" style="width: 900px; height: 500px;"></div>

    public by dave83  5084  15  8  6

    Touch down event binding in Kivy framework

    This code shows how to handle a touch event in the python Kivy framework. This snippet will generate a simple GUI, with 2 standard buttons and a custom button, where to bind the press event. Any Kivy property has a default on_ event. This event is called when the value of the property is changed. In this case the on_touch_down(self, touch) meth
    from import App
     from kivy.uix.widget import Widget
     from kivy.uix.button import Button
     from kivy.uix.boxlayout import BoxLayout
     from import ListProperty
     class RootWidget(BoxLayout):
         def __init__(self, **kwargs):
             super(RootWidget, self).__init__(**kwargs)
             self.add_widget(Button(text='btn 1'))
             cb = CustomBtn()
             self.add_widget(Button(text='btn 2'))
         def btn_pressed(self, instance, pos):
             print ('pos: printed from root widget: {pos}'.format(pos=pos))
     class CustomBtn(Widget):
         pressed = ListProperty([0, 0])
         def on_touch_down(self, touch):
             if self.collide_point(*touch.pos):
                 self.pressed = touch.pos
                 # we consumed the touch. return False here to propagate
                 # the touch further to the children.
                 return True
             return super(CustomBtn, self).on_touch_down(touch)
         def on_pressed(self, instance, pos):
             print ('pressed at {pos}'.format(pos=pos))
     class TestApp(App):
         def build(self):
             return RootWidget()
     if __name__ == '__main__':

    public by dave83  2939  0  6  9

    Example of java servlet

    This code shows a simple web servlet application in java. A servlet is a web component hosted in a servlet container and generates dynamic content. You can run it using JBoss or Tomcat web servers.
    package servletPkg;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     * Servlet implementation class AccountServlet
    public class AccountServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
         * @see HttpServlet#HttpServlet()
        public AccountServlet() {
            // TODO Auto-generated constructor stub
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		try (PrintWriter out = response.getWriter()) {
    			out.println("<h1>My First Servlet</h1>");
    			//. . .
    			} finally {
    			//. . .
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub

    public by dave83  2600  1  6  2

    Client socket in Java

    This code shows a simple socket client in java. The client will connect to the socket server and get the date string.
    import javax.swing.JOptionPane;
     * Trivial client for the date server.
    public class DateClient {
         * Runs the client as an application.  First it displays a dialog
         * box asking for the IP address or hostname of a host running
         * the date server, then connects to it and displays the date that
         * it serves.
        public static void main(String[] args) throws IOException {
            String serverAddress = JOptionPane.showInputDialog(
                "Enter IP Address of a machine that is\n" +
                "running the date service on port 9090:");
            Socket s = new Socket(serverAddress, 9090);
            String hostAddress = s.getInetAddress().getHostAddress();
            String hostName = s.getInetAddress().getHostName();
            BufferedReader input =
                new BufferedReader(new InputStreamReader(s.getInputStream()));
            StringBuilder sb = new StringBuilder();
            JOptionPane.showMessageDialog(null, sb.toString());

    public by dave83  3325  5  7  5

    Server socket in Java

    This is a simple server socket in java. The server will accept the client request and return the date string.
    import java.util.Date;
     * A TCP server that runs on port 9090.  When a client connects, it
     * sends the client the current date and time, then closes the
     * connection with that client.  Arguably just about the simplest
     * server you can write.
    public class DateServer {
         * Runs the server.
        public static void main(String[] args) throws IOException {
            ServerSocket listener = new ServerSocket(9090);
            try {
                while (true) {
                    Socket socket = listener.accept();
                    try {
                        PrintWriter out =
                            new PrintWriter(socket.getOutputStream(), true);
                        out.println(new Date().toString());
                    } finally {
            finally {

    List Complete ( 10 snippets total )

    • Public Snippets
    • Channels Snippets