Archive

Archive for the ‘Java’ Category

Session Tracking In Swing Applications

September 24, 2009 Abhijeet Iraj Leave a comment

Session handling is pretty common in web applications. Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.  But if you have swing application and want to track the session how to do that?

Here is the scenario – Suppose you have a swing based kiosk application. User logs in to the application and does some operations.  Now for some reason he doesn’t perform any operation for 3-4 minutes then for security reasons we need to somehow log out from the swing application.

This can be achieved with the help of Swing timers and AWT default toolkit.

Here are the steps

    • When user logs in start the swing timer by passing SESSION_TIMEOUT value and ActionListener (to handle timeout event).
    • Add AWTEventListener to AWT toolkit with AWTEvent.MOUSE_EVENT_MASK and AWTEvent.KEY_EVENT_MASK. This will track only mouse events and key events.
    • Whenever AWT event occurs (that means user performed some action) restart the timer.
    • When the system is idle for SESSION_TIMEOUT time, timer will call actionPerformed method of its ActionListener.It means session timeout occured and you need to logout.
      import java.awt.AWTEvent;
      import java.awt.Toolkit;
      import java.awt.event.AWTEventListener;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      
      import javax.swing.Timer;
      
      /**
       * @author airaj
       *
       */
      public class SystemTimeoutClient implements AWTEventListener, ActionListener
      {
          private int SESSION_TIMEOUT = 240000; // 4 minutes
          private static SystemTimeoutClient client = null;
          private Timer timer;
      
          private SystemTimeoutClient()
          {
          }
      
          public static SystemTimeoutClient getSystemTimeoutClient()
          {
              if (client == null)
              {
                  client = new SystemTimeoutClient();
              }
              return client;
          }
      
          public void trackSessionTimeout()
          {
              timer = new Timer(SESSION_TIMEOUT, this);
              timer.setInitialDelay(SESSION_TIMEOUT);
              timer.setRepeats(false);
              timer.start();
              trackSystemEvents();
          }
      
          public void stopSessionTracking()
          {
              if (timer.isRunning())
              {
                  timer.stop();
              }
          }
      
          private void trackSystemEvents()
          {
              Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK + AWTEvent.KEY_EVENT_MASK);
          }
      
          @Override
          public void eventDispatched(AWTEvent event)
          {
              // User action detected. Restart the timer
              if (timer.isRunning())
              {
                  timer.restart();
              }
          }
      
          @Override
          public void actionPerformed(ActionEvent e)
          {
              // Session Timeout occured. Close resources and log out from system. 
      
          }
      }
      

      Spring MVC Web Portal

      September 2, 2009 Abhijeet Iraj Leave a comment

      Recently we migrated from Backbase based portal to Spring MVC based portal for our kiosk transaction system. This will evolve as Offline system (see davids post on this here).

      We mainly used Spring to build this offline system because it’s lightweight, easy to use, easy to test and it allows to configure and compose complex application from simpler components.

      portal

      Here is the technology stack which we are using to build this offline system

      • Spring MVC: Part of spring and MVC  based Framework for building robust web applications
      • Spring Webflow: Built on Spring MVC and provides the infrastructure for building and running rich web application.
      • JQuery: Fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
      • Blueprintcss: CSS framework which aims to cut down on your development time.
      • JMesa: Dynamic HTML table rendering API/Tag library that allows you to filter, sort, paginate, export and edit your data however you need to.
      • Sitemesh: Web-page layout and decoration framework and web-application integration framework to aid in creating large sites consisting of many pages for which a consistent look/feel, navigation and layout scheme is required.
      • Hibernate: Powerful, high performance object/relational persistence and query service.
      • Maven: Software project build and  management tool.
      • MySQL: Most popular open source database.
      • SpringSource ToolSuite: Eclipse-powered development environment for building Spring-powered enterprise applications.
      Categories: Spring, web Tags: , , , ,

      Swing Event Dispatcher Thread

      September 1, 2009 Abhijeet Iraj Leave a comment

      Even though swing is very important part of the Java platform, truth is that its not thread safe. That means swing component methods called from multiple threads can cause thread interference or memory consistency errors. There are some exceptions to this. There are some swing component methods which are “thread safe” which can be safely invoked from any thread.

      Reason why swing is not thread safe is that any attempt to create a thread-safe GUI library faces some fundamental problems. For more on this issue, see the following entry in Graham Hamilton’s blog: MultiThreaded toolkits: A failed dream?

      Because of this swing event handling code execution as well as component repaint happens on a special thread known as the event dispatch thread. All the Swing component methods which are not thread safe must be invoked from this event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

      EDT

      There are two fundamental things to understand about Swing and threads:

      1. Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive. The EDT is busy executing your task and hence can’t process GUI events.
      2. Swing components should be accessed on the Event Dispatch Thread only. To access components from other threads, you must use SwingUtilities. invokeAndWait, SwingUtilities. invokeLater or SwingWorker.
      Categories: Java, RIA, Swing Tags: , , ,

      MEI Cash Acceptor with Bunch Note Feeder

      August 29, 2009 Abhijeet Iraj Leave a comment

      Frankly speaking i had never used cash acceptor in my life since in India that technology is not used much. But recently i got a chance to integrate MEI CASHFLOW® SC Series note acceptor with BNF in our system at work and it was really a nice experience. This is one of the world’s most technically advanced cash acceptor.

      Cash Acceptor

      Because of bunch note feeder (BNF) user can deposit cash more efficiently by placing a bundle of up to 30 notes into a BNF.

      Before starting integration, one thing which was really important was to change MEI Cash Acceptor from Stand-Alone mode to EBDS mode. In Stand-Alone mode the communication between the SC and API will not work.

      Integration using MEI provided java api was straightforward..

      /**
       * @author airaj
       *
       */
      public class MEICashAcceptor extends CashAcceptor
                                                 implements AcceptorEventListener
      {
          // serial port to which device is connected
          private String serialPort = "/dev/ttyS3";
      
          private Acceptor cashAcceptor = null;
      
          // connect to the device
          public void connect()
          {
              cashAcceptor = new Acceptor();
              cashAcceptor.addAcceptorEventListener(this);
              Acceptor.listPorts();
              try
              {
                  cashAcceptor.open(serialPort, PowerUp.A);
              }
              catch (AcceptorException e)
              {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      
          // enable acceptor so that it accepts bills
          public void enable()
          {
              cashAcceptor.setEnableAcceptance(true);
          }
      
          // disable acceptor so that it stops accepting bills
          public void disable()
          {
              cashAcceptor.setEnableAcceptance(false);
          }
      
          // This method gets called when any device event occurs
          public void acceptorEventOccurred(AcceptorEvent evt)
          {
              if (evt.getDescription() == null)
              {
                  return;
              }
              if (evt instanceof EscrowEvent)
              {
                  // Event generated for bill Escrow
                  if (DocumentType.Bill.equals(cashAcceptor.getDocType()))
                  {
                      Bill b = cashAcceptor.getBill();
                      try
                      {
                          // stack the bill
                          cashAcceptor.escrowStack();
                      }
                      catch (AcceptorException e)
                      {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
              }
              else if (evt instanceof StackedEvent)
              {
                  // Event generated when a document is stacked.
                  if (DocumentType.Bill.equals(cashAcceptor.getDocType()))
                  {
                      Bill bill = cashAcceptor.getBill();
                      String country  = bill.getCountry();
                      String value = bill.getValue();
                  }
              }
              else if (evt instanceof CheatedEvent)
              {
                   // Event generated when the device detects a cheat attempt.
              }
              else if (evt instanceof JamDetectedEvent)
              {
                  // Event generated when the device detects a jam.
              }
              else if (evt instanceof StackerFullEvent)
              {
                  // Event generated when the device stacker is full.
              }
          }
      
      }

      You can view MEI CASHFLOW Bill acceptor with BNF demo here