Advertisement

Sri Lanka's First and Only Platform for Luxury Houses and Apartment for Sale, Rent

Friday, February 28, 2014

Custom Hibernate NamingStrategy

As part of my work my lead asked me to find a way to dynamically pre-pend a prefix to all the Hibernate Entities which uses JPA @Entity Annotation. This is to create a way to implement a flexible, customizable way to generate Entities which can be used across different projects by just changing the prefix.

So after some googling I found a link [1] where it is explained how to use a Custom NamingStrategy but it didn't quite do the exact my lead was looking for because it worked only with @Entity annotated classes which do not have @Table annotation. But my lead wanted to keep the @Table annotation and he wanted the @JoinTable annotation names also to be prefixed.

So after some trial and error I came up with the following changes with a Custom implementation of org.hibernate.cfg.ImprovedNamingStrategy and one hibernate configuration.

import org.hibernate.cfg.ImprovedNamingStrategy;

public class CustomNamingStrategy extends ImprovedNamingStrategy {
    
    private String prefix = "customprefix_";
    
    public String tableName(String tableName) {
        return _prefix(super.tableName(tableName));
    }
    
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    
    private String _prefix(String table) {
        return prefix + table;
    }

}


and following configuration for hibernate

<prop key="hibernate.ejb.naming_strategy">CustomNamingStrategy</prop>

  1. http://www.petrikainulainen.net/programming/tips-and-tricks/implementing-a-custom-namingstrategy-with-hibernate/

Thursday, February 27, 2014

Spring Security Custom FilterChainProxy Configuration

I have worked with Spring Security extensively for the past six months as part of my current job. But my work mostly involved configuring the most important FilterChainProxy of Spring Security using namespaces. But I wanted to dig deeper and to see how the internals of the Spring Security FilterChainProxy so I completely read the Spring Security Documentation for version 3.1.4.RELEASE and realized that in fact I can configure a custom FilterChainProxy given that I define the following filters which are a must have for the FilterChainProxy.
  1. SecurityContextPersistenceFilter
  2. ExceptionTranslationFilter
  3. FilterSecurityInterceptor
The document had a small snippet of declaring these inside of the custom FilterChainProxy but that didn't show the complete set of beans required to get the FilterChainProxy working. So I wanted to get the bottom of it so I configured it myself by going through documentation.

Basically you can have a working FilterChainProxy with the name springSecurityFilterChain by just using the following Spring Declarations using security namespace.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

     <security:http security="none" pattern="/resources/**" />
     <security:http auto-config="true" use-expressions="true">
        <security:intercept-url pattern="/login*"
            access="isAnonymous()" />
        <security:intercept-url pattern="/**"
            access="isAuthenticated()" />
        <security:form-login login-page="/login"
            default-target-url="/" always-use-default-target="true"
            authentication-failure-url="/login?error=true" />
        <security:logout invalidate-session="true"
            delete-cookies="JSESSIONID" logout-success-url="/login" />
    </security:http>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider
            user-service-ref="userService">
            <security:password-encoder hash="md5"
                base64="true">
                <security:salt-source user-property="salt" />
            </security:password-encoder>
        </security:authentication-provider>
    </security:authentication-manager>
    
</beans>

But as you can see here I have set auto-config attribute of security:http namespace to true in order to generate all the required configurations of Filters for me. This is easy but not the most flexible declaration.

So the same thing can be declared explicitly without using the security namespace as follows.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider
            user-service-ref="userService">
            <security:password-encoder hash="md5"
                base64="true">
                <security:salt-source user-property="salt" />
            </security:password-encoder>
        </security:authentication-provider>
    </security:authentication-manager>

    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
        <constructor-arg>
            <list>
                <security:filter-chain pattern="/login**" filters="none"/>
                <security:filter-chain pattern="/resources/**" filters="none"/>
                <security:filter-chain pattern="/**"
                    filters="securityContextPersistenceFilterWithASCTrue,    
                                                          logoutFilter,                                                
                                                             formLoginFilter,                                                              
                                                             formLoginExceptionTranslationFilter,
                                                             filterSecurityInterceptor" />
            </list>
        </constructor-arg>
    </bean>

    <bean id="securityContextPersistenceFilterWithASCTrue"
        class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
        <constructor-arg>
            <bean class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
        </constructor-arg>
    </bean>
    
    <bean id="formLoginExceptionTranslationFilter"
        class="org.springframework.security.web.access.ExceptionTranslationFilter">
        <constructor-arg>
            <bean
                class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
                <constructor-arg value="/login"/>                
            </bean>
        </constructor-arg>
        <property name="accessDeniedHandler">
            <bean
                class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
                <property name="errorPage" value="/exception" />
            </bean>
        </property>
    </bean>

    <bean id="formLoginFilter"
        class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="allowSessionCreation" value="true"/>
        <property name="authenticationSuccessHandler">
            <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
                <constructor-arg value="/"/>
                <property name="alwaysUseDefaultTargetUrl" value="true"/>
            </bean>
        </property>
        <property name="authenticationFailureHandler">
            <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                <constructor-arg value="/login?error=true"/>
            </bean>
        </property>
    </bean>

    <bean id="filterSecurityInterceptor"
        class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="accessDecisionManager" ref="accessDecisionManager" />
        <property name="runAsManager" ref="runAsManager" />
        <property name="securityMetadataSource">
            <security:filter-security-metadata-source use-expressions="true">
                <security:intercept-url pattern="/**"
                    access="isAuthenticated()" />
            </security:filter-security-metadata-source>
        </property>
    </bean>

    <bean id="accessDecisionManager"
        class="org.springframework.security.access.vote.AffirmativeBased">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.access.vote.RoleVoter"/>
                <bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
            </list>
        </constructor-arg>
        <property name="allowIfAllAbstainDecisions" value="false"/>
    </bean>

    <bean id="runAsManager"
        class="org.springframework.security.access.intercept.RunAsManagerImpl">
        <property name="key" value="TELCO_RUN_AS"/>
    </bean>
        
    <bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
        <constructor-arg value="/login"/>        
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler">
                    <constructor-arg>
                        <list>
                            <value>JSESSIONID</value>
                        </list>                        
                    </constructor-arg>
                </bean>
                <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
            </list>
        </constructor-arg>
    </bean>
    
</beans>


Wow Spring Security namespace is a real life saver when it comes to configuring right? but critics might ask why declare explicitly when it generates.

  1. Gives more control over the configurations
  2. Enables to understand the flow
  3. Enables flexibility
For this Custom FilterChainProxy to work it must be named similar to the filter name of DelegatingFilterProxy in the web.xml configuration, for example with the following configuration;

<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
The explicitly declared FilterChainProxy must be named springSecurityFilterChain.

Trackbacks/Pings

Saturday, February 1, 2014

Interfacing Force Sensing Resistor with Arduino

Today I got the time to test a Arduino compatible component I had for a long time. It is a 1.5" Force Sensing Resistor (FSR) cable of measuring the force applied onto its surface area. The following shows a really small demo/tutorial on how to connect the FSR to Arduino and read its force value. More details on the FSR can be found here.


Above is the Fritzing layout of the connected Arduino and FSR. And below you can see the photo of the FSR connected.


The following the Arduino sketch which reads the value of the FSR and prints in the Serial.

int value = 0;

void setup() {
  Serial.begin(9600); 
}

void loop() {
  value = analogRead(A0);
  Serial.print("Force : ");
  Serial.print(value, DEC);
  Serial.print("\n");
  delay(100); 
}

Output of the Serial is as follows.



References 
  1. http://bildr.org/2012/11/force-sensitive-resistor-arduino/
Trackbacks/Pings

Monday, January 13, 2014

Face following RC Car using Android + Arduino + USB Host Shield

I have been working with an Arduino + RC Car setup for a quite a sometime in this post and this post. Finally I wanted to do something with it by integrating it to an Android phone. After some googling I found that I can connect the Android + Arduino using USB Host Shield in two different ways. One is where the Arduino + USB Host Shield acts as an Android Accessory (I have a done a post using that too) and the other one is where the Arduino + USB Host Shield is connected through Android Debug Bridge (ADB). I used the ADB method because I have already tried the Accessory method.

The uniqueness in this approach is that many people have done RC Car Hacks using Arduino to control the Remote Control not directly the car itself. The following hack directly controls the car instead of sending commands using the Remote control.

So I have already connected the RC Car's control pins to Arduino (Check out the previous posts) and so started coding my arduino sketch which is below.

 #include <SPI.h>  
 #include <Adb.h>  
 #define FW_PIN 3  
 #define BW_PIN 4  
 #define LF_PIN 5  
 #define RT_PIN 6  
 // Adb connection.  
 Connection * connection;  
 // Elapsed time for ADC sampling  
 long lastTime;  
 void actuate(int pin);  
 void turnLeft();  
 void turnRight();  
 // Event handler for the shell connection.   
 void adbEventHandler(Connection * connection, adb_eventType event, uint16_t length, uint8_t * data)  
 {  
  int i;  
  // Data packets contain two bytes, one for each servo, in the range of [0..180]  
  if (event == ADB_CONNECTION_RECEIVE)  
  {  
   Serial.println(data[0], DEC);  
   if(data[0] == 0x01) {  
     actuate(FW_PIN);  
   } else if(data[0] == 0x02) {  
     actuate(BW_PIN);   
   } else if(data[0] == 0x03) {  
     turnLeft();   
   } else if(data[0] == 0x04) {  
     turnRight();   
   }  
  }  
 }  
 void setup()  
 {  
  Serial.begin(9600);  
  // Note start time  
  lastTime = millis();  
  pinMode(FW_PIN, OUTPUT);  
  pinMode(BW_PIN, OUTPUT);  
  pinMode(LF_PIN, OUTPUT);  
  pinMode(RT_PIN, OUTPUT);  
  // Initialise the ADB subsystem.   
  ADB::init();  
  // Open an ADB stream to the phone's shell. Auto-reconnect  
  connection = ADB::addConnection("tcp:4567", true, adbEventHandler);   
 }  
 void loop()  
 {  
  lastTime = millis();  
  // Poll the ADB subsystem.  
  ADB::poll();  
  delay(50);  
 }  
 void actuate(int pin) {  
  digitalWrite(pin, HIGH);  
  delay(50);  
  digitalWrite(pin, LOW);   
 }  
 void turnLeft() {  
  digitalWrite(LF_PIN, HIGH);  
  actuate(FW_PIN);  
  digitalWrite(LF_PIN, LOW);  
 }  
 void turnRight() {  
  digitalWrite(RT_PIN, HIGH);  
  actuate(FW_PIN);  
  digitalWrite(RT_PIN, LOW);  
 }  

And for the Android Face detection app I made use of OpenCV Sample - face detection app which is available in the OpenCV for Android SDK version 2.4.7 samples directory. I added the microbridge server source codes which I downloaded from ADB Microbridge google code site and did slight following modifications to OpenCV Android Face detection app.

AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET">  

Because the Microbridge server is a TCP Server which listens on port 4567.

FdActivity.java


1:  package org.opencv.samples.facedetect;  
2:  ...  
3:  public class FdActivity extends Activity implements CvCameraViewListener2 {  
4:       ...       
5:       private Server server;  
6:       /** Called when the activity is first created. */  
7:       @Override  
8:       public void onCreate(Bundle savedInstanceState) {  
9:            ...  
10:            // Create TCP server  
11:            server = null;  
12:            try {  
13:                 server = new Server(4567);  
14:                 server.start();  
15:            } catch (IOException e) {  
16:                 Log.e("microbridge", "Unable to start TCP server", e);  
17:                 System.exit(-1);  
18:            }            
19:       }  
20:       public Mat onCameraFrame(CvCameraViewFrame inputFrame) {  
21:            ...  
22:            Rect firstFace = null;  
23:            if(facesArray.length > 0) { 
24:                 Size size = mRgba.size(); 
25:                 firstFace = facesArray[0];  
26:                 byte[] data = new byte[1];  
27:                 if(firstFace.x > size.width / 2) {  
28:                      data[0] = 0x03;  
29:                 } else if(firstFace.x < size.width / 2) {  
30:                      data[0] = 0x04;  
31:                 }   
32:                 try {  
33:                      server.send(data);  
34:                 } catch (IOException e) {  
35:                      // TODO Auto-generated catch block  
36:                      e.printStackTrace();  
37:                 }  
38:            }  
39:            return mRgba;  
40:       }       
41:  }  

The logic I have used here is if the First Detected Face is in the right half of the image then turn right or else turn left and go forward. In order for Android and Arduino to communicate using ADB USB Debugging must be enabled in Android.

Finally you can see the entire thing working together in the below video.





The USB cable to Arduino is only connected to power up the whole unit. I tried a 9v Battery and you can see the battery connector connected to the Arduino but the phone was also drawing power from the battery thus it wasn't enough to power up the system. But I think a 12v Battery may be sufficient enough.

If anyone need the full source codes you can find it at github.com/shazin/facecar

References
Trackbacks/Pings

Sunday, December 22, 2013

Raspberry pi LED Blinker

Ever since I came to Malaysia my inventive side is becoming more and more sharper. Mainly because of the Electronic components available easily in Malaysia for affordable prices. I bought a myself a Raspberry pi Model B with a Transparent casing + 8 Gb SSD Card with Preloaded Noobs for just MYR 199 (USD 60.53).

Furthermore I went to an area called Jalan Pasar in Pudu where there are lots and lots of Electronic shops which sells all sorts of components. I am waiting to do more hacks and hobby projects in the future but to start off I did a small LED Blinker project using Raspberry pi.

The following steps needs to be carried out to Run the LED Blinker in Raspberry pi.
  • Login to Raspberry pi
  • Open a LXTerminal window
  • Download the python GPIO library
wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.4.1a.tar.gz



  • Untar the Tar file

  • tar zxvf RPi.GPIO-0.4.1a.tar.gz



  • Go into untared directory

  • cd RPi.GPIO-0.4.1a



  • Install GPIO for python

  • sudo python setup.py install

    If you get errors during the installation process then you must first do the following


    source/py_gpio.c:23:20: fatal error: Python.h: No such file or directory
    Compilation terminated.
    error: command 'gcc' failed with exit status 1
    
    • Run apt-get update
    sudo apt-get update
    
    • The install python dev (Debian)
    sudo apt-get install python-dev
    

    • Pidora 

    sudo yum -y install python-devel

    After that do the following wiring where an LED ground is connected using a 1K Resistor to the Raspberry pi GND pin 6. And pin 7 GPIO 4 is connected to the LED Positive.


    Then copy the following code to a text editor and save it as blink_led.py

    import RPi.GPIO as GPIO 
    import time 
    import threading
    
    GPIO.setmode(GPIO.BOARD) 
    GPIO.setup(7, GPIO.OUT) 
    
    class Blinker(threading.Thread):
        def __init__(self, speed, times):    
            threading.Thread.__init__(self);
            self.speed = speed;    
            self.times = times;
    
        def run(self):
            for i in range(0,self.times):
                print "Time : %d" % ((i+1))
                GPIO.output(7,True)
                time.sleep(self.speed)
                GPIO.output(7,False)
                time.sleep(self.speed)
            print "Blinking Complete!" 
            GPIO.cleanup()    
    
    blinker = Blinker(1, 10)
    blinker.start()
    
    • Finally close the LXTerminal and open a new one and execute the following
    sudo python blink_led.py
    

    Everything working together


    References
    • http://www.thirdeyevis.com/pi-page-1.php#gpio-setup
    • http://www.thirdeyevis.com/pi-page-2.php
    • http://www.raspberrypi.org/phpBB3/viewtopic.php?f=31&t=13003

      Saturday, October 19, 2013

      Giving RC Car a simple brain using Arduino + Ping (Ultrasonic) Sensor

      It has been quite a sometime from my last post. Mainly due to busy schedules and settling down in Malaysia I would say. But I came to back to Sri Lanka on vacation and got time on a lazy Saturday morning and put together a small Arduino + RC Car setup.

      In one of my previous posts I teared down a RC Car and explained the internals of that. Working further on that I managed to write a small Arduino sketch to work with a Ping Sensor to give a simple brain to the RC Car. What makes this distinguishable from other RC Car + Arduino hacks is that, Almost all other hacks use the Arduino to control the Remote Control not the Car itself. But I wanted to control the car directly using the Arduino so that I can eventually achieve the goal of using an Android phone connected to Arduino using a USB Host Shield to act as the Smart Brain of the RC Car.

      The following items were used in setting up this prototype.
      1. 1 Arduino UNO Rev 3
      2. 1 Breadboard
      3. 1 DFRobot URM37 V3.2 Ultrasonic Sensor
      4. Some Jumper Cables
      5. And of course a RC Car
      Following is the Arduino Sketch. The DFRobot Ultrasonic Sensor was used in TTL Mode and Arduino Pin 3 was connected to PWM and 5 was connected to COMP/TRIG of the Sensor. The Arduino Digital Out pin 11 was used for forward actuating and pin 10 was used for backward actuating of the RC Car . I have soldered jumper cables to the RC Car so that they can be easily used and distinguished. 

      int URPWM = 3; 
      int URTRIG=5; 
      int forwardPin = 11;
      int backwardPin = 10;
       
      unsigned int Distance=0;
      uint8_t EnPwmCmd[4]={0x44,0x02,0xbb,0x01};    
      boolean forward = false;
      boolean backward = false;
      int minDistanceCm = 5;
      
      void setup(){                                 
        pinMode(URTRIG,OUTPUT);                     
        digitalWrite(URTRIG,HIGH);                  
        
        pinMode(URPWM, INPUT);                      
        pinMode(forwardPin, OUTPUT);
        pinMode(backwardPin, OUTPUT);
      }
       
      void loop()
      {
         digitalWrite(URTRIG, LOW);
         digitalWrite(URTRIG, HIGH);               
         unsigned long DistanceMeasured=pulseIn(URPWM,LOW);
           
         if(DistanceMeasured==50000){              
               
         } else {
            Distance=DistanceMeasured/50;           
         }
        
         if(Distance > minDistanceCm) {
            forward = true;  
            backward = false;
         } else {
            forward = false;
            backward = true; 
         }
         
         if(forward) {
            digitalWrite(forwardPin, HIGH);
            delay(100);
            digitalWrite(forwardPin, LOW);
         } else {
            digitalWrite(backwardPin, HIGH);
            delay(200);      
            digitalWrite(backwardPin, LOW);     
         }
         delay(400);
      }                      
       
      
      

      The video below shows the prototype in action. The USB cable is only used to supply electricity for the Arduino. Adding a battery will eliminate the need for the USB cable.


      This prototype is by no means complete. I did this so that I can achieve the goal of using an Android phone with Camera + GPS as the brain. But this step was a necessary and crucial learning stage for me. Constructive criticism is always welcome.

      References
      1. DFRobot Ultrasonic Sensor Manual - http://www.dfrobot.com/wiki/index.php/URM37_V3.2_Ultrasonic_Sensor_(SKU:SEN0001)

      Monday, June 3, 2013

      New Country, New Job!

      I got to know about a job in Malaysia in the month of March while I was working at Virtusa. At that point I didn't know in which company I would be working in, but I wanted to work in a foreign country so applied. Days later I got a call from an agent in Sri Lanka that some people would be coming down from Malaysia for the interview and I would be called within 2 weeks time. To be honest I wasn't sure of what he said but kept my fingers crossed.

      Right after two weeks I did get a call from the agent saying I have an interview on 4th of April at Galadari Hotel Colombo. I went there and there were three people from Malaysia from the company MIMOS including the CTO.

      MIMOS is Malaysia's National Research and Development Institute for ICT. It comes directly under the purview of MOSTI, Ministry of Science, Technology and Innovation. It seemed a really good offer for me and I did quite well in the interview due to my preparedness. The CTO was impressed of my little Arduino Projects and during the interview I knew that I had at least 70% chance of getting in.

      After two more weeks I got the news that I have been selected out of 14 interviewees as one of the potential employees. I was over the moon and started preparing to come to Malaysia. After more than one month of preparing I finally landed in Malaysia on 02nd of June 2013 at 7:15 a.m.

      Now I am temporarily residing at Bukit Jalil which is closed to Technology Park Malaysia which is where MIMOS is located.

      All thanks to god for giving me such a wonderful opportunity.