Thursday, October 24, 2013

What are the defined fields for each salesforce object

In salesforce(www.salesforce.com) there are many objects like accounts, users, leads...Etc. When using REST API or when executing a SOQL we need to give the exact name of the field.
Since salesforce does not support SELECT * from XXXX

This is way I used to extract necessary information from salesforce

1. Login to salesforce
2. Go to Setup->Develop API
3. Generate Partner WSDL (If you working with sandbox environment it might gives some errors but partner WSDL is sufficient)
4. Generate stub jar file Ref :http://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_code_set_up_client.htm
5. Use the following code sample

       ConnectorConfig sfconfig = new ConnectorConfig();
        sfconfig.setUsername("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        sfconfig.setPassword("xxxxxxxxxxxxxxxxxxxxxxQNx26Lb4PTw");        
        PartnerConnection  connection = Connector.newConnection(sfconfig);
         DescribeSObjectResult[] describeSObjectResults =  connection.describeSObjects(
                   new String[] { "account"});
        for (int i=0;i < describeSObjectResults.length; i++)
        {
            DescribeSObjectResult desObj = describeSObjectResults[i];
            String objectName = desObj.getName();
            com.sforce.soap.partner.Field[] fields = desObj.getFields();
            if (desObj.getActivateable()) System.out.println("\tActivateable");
            for(int j=0;j < fields.length; j++)       {                        
                com.sforce.soap.partner.Field field = fields[j];
                System.out.println("\tField: " + field.getName());
                System.out.println("\t\tLabel: " + field.getLabel());
                if (field.isCustom()) 
                    System.out.println("\t\tThis is a custom field.");
                System.out.println("\t\tType: " + field.getType());
                if (field.getLength() > 0)
                    System.out.println("\t\tLength: " + field.getLength());
                if (field.getPrecision() > 0)
                    System.out.println("\t\tPrecision: " + field.getPrecision());
                if (field.getType() == FieldType.picklist)
                {                            
                  
                    PicklistEntry[] picklistValues = field.getPicklistValues();
                    if (picklistValues != null && picklistValues[0] != null)
                    {
                        System.out.println("\t\tPicklist values = ");
                        for (int k = 0; k < picklistValues.length; k++)
                        {
                            System.out.println("\t\t\tItem: " + picklistValues[k].getLabel());
                        }
                    }
                }
                if (field.getType() == FieldType.reference)
                {                            
                   
                    String[] referenceTos = field.getReferenceTo();
                    if (referenceTos != null && referenceTos[0] != null)
                    {
                        System.out.println("\t\tField references the following objects:");
                        for (int k = 0; k < referenceTos.length; k++)
                        {
                            System.out.println("\t\t\t" + referenceTos[k]);
                        }
                    }
                }
            }            
        }

Wednesday, October 16, 2013

Creating a new remote access application in Salesforce

Create OAuth Token and secret from Salesforce


If your planning to get Sales force information from REST API you will find that creating Remote Access app by following http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_REST_API is not working as describe

Here how it goes

Log in to Salesforce.com with your developer account, navigate to Setup ➤ Develop ➤ Remote Access, 
and click New to create a new remote access application if you have not already done so.

This is not working under the new Salesforce changes

Once you click Remote Access it will say 

Remote Access Objects have been moved to Applications. You'll be redirected to that page in five seconds, or you can click Take Me There to go now. 

Then you will be forword to Create -> Apps section

Go to Connected Apps and create new



Once you save this you can get the OAuth token and secret

Saturday, October 12, 2013

Read and process large one line JSON file

My initial problem was to read and process large one line JSON file. with traditional approaches it took 3 hours to read and process the JSON file. So I have done research in this area and found a way to read the JSON file chunk by chunk, now I can do the same thing in 5 min

Bellow I have break the JSON which had 200000 elements in to 20 * 10000 chunks

public static void jsonFileReader() throws JsonParseException, IOException{
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createJsonParser(new File("MyHugeJSonFile.json"));
JsonToken current;

current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
int i = 0;
while (jp.nextToken() != JsonToken.END_OBJECT) {

String fieldName = jp.getCurrentName();
current = jp.nextToken();
if (fieldName.equals("employees")) {

if (current == JsonToken.START_ARRAY) {
List<String> strings = new ArrayList<String>();
String previousValue = "";
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node = jp.readValueAsTree();
String valueAsText = node.get("id").getTextValue();
strings.add(valueAsText);
if((strings.size() == 100)) {
String valueAsText1 = null;
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node1 = jp.readValueAsTree();
valueAsText1 = node1.get("id").getTextValue();
if(!previousValue.equals(valueAsText1)) {
break;
} else {
strings.add(valueAsText1);
}
}
int j =0;
for (Iterator<String> iterator  = strings.iterator(); iterator.hasNext();) {
i = i + 1;
j = j + 1;
String string = (String) iterator .next();
System.out.println(i+" -- "+j+" --> "+string);
strings = new ArrayList<String>();
}
System.out.println("-------------------------------------------------------------");
strings.add(valueAsText1);
}
previousValue = valueAsText;
}
int j =0;
for (Iterator<String> iterator  = strings.iterator(); iterator.hasNext();) {
i = i + 1;
j = j + 1;
String string = (String) iterator .next();
System.out.println(i+" -- "+j+" --> "+string);
strings = new ArrayList<String>();
}
System.out.println("-------------------------------------------------------------");

} else {
System.out.println("Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
System.out.println("Unprocessed property: " + fieldName);
jp.skipChildren();
}
}

System.out.println("Total Record size " + i);
}

Sunday, October 6, 2013

Insert large data sets with Hibernate

Hibernate is a generic ORM framework and when it comes to very specific scenarios you may face difficulties. Specially when try to insert/write large data set(more than 1 million records) to the database at once.

But there are ways to get away from that

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

int i = 0;
for (Iterator<T> iterator = persistenceObject.iterator(); iterator.hasNext();) {
  i++;
  session.saveOrUpdate(iterator.next());
  if (i % 50 == 0) {
session.flush();
session.clear();
  }
}
tx.commit();

session.close();


Above example write 50 records at once not 1 million at once. If you have more efficient ways please comment on this

Monday, September 30, 2013

Free Verisign Certificate for Amazon EC2 instance

How to get a signed free Certificate from Verisign for setup https on Amazon EC2 instance

1. Install openssl in your environment
2. Create a RSA key
>openssl genrsa -out test-xxx.elasticbeanstalk.com.key 2048
Loading 'screen' into random state - done
Generating RSA private key, 2048 bit long modulus
..........................................................+++
.........................+++
e is 65537 (0x10001)

The generated file should look like below

-----BEGIN RSA PRIVATE KEY-----
Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END RSA PRIVATE KEY-----

3. Create certifcate signing request (CSR) with generated RSA private key
>openssl req -new -key test-xxx.elasticbeanstalk.com.key -out test-gatekeeper-api-v1.elasticbeanstalk.com.csr
Loading 'screen' into random state - done
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:AU
State or Province Name (full name) [Some-State]:Vic
Locality Name (eg, city) []:Melbourne
Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyFreeTestCompany
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:Suraj
Email Address []:scsbatu@yahoo.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:test1234
An optional company name []:

4. Verify the csr
>openssl req -noout -text -in test-gatekeeper-api-v1.elasticbeanstalk.com.csr
Certificate Request:
Data:
Version: 0 (0x0)
Subject: C=AU, ST=Vic, L=Melbourne, O=MyFreeTestCompany, OU=IT, CN=Suraj/emailAddress=scsbatu@yahoo.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:dd:24:cc:61:69:5f:66:58:a2:9f:98:d4:31:f0:
fb:10:ff:12:73:cf:66:ce:4f:3d:3a:f1:8c:47:25:
25:31:86:c0:ee:28:d0:62:65:34:73:7a:61:f1:f1:
7f:85:92:e2:6a:2c:96:8f:2d:63:dc:b2:a6:8f:95:
a9:8e:dc:1a:05:50:a7:1e:50:3b:d6:ad:ad:da:77:
ab:7e:5b:71:04:50:69:2a:7a:77:0d:f6:50:22:0f:
12:33:08:61:1a:a9:1c:82:54:df:9b:d2:f2:3e:ee:
00:11:4f:23:42:fb:a8:e1:3d:08:26:eb:08:45:c8:
67:f2:14:66:95:2c:a6:e0:66:26:48:52:d7:b8:37:
4a:ca:8e:76:d5:9f:e3:b7:bb:df:71:2a:74:58:9d:
62:9c:c6:a1:57:31:9f:3b:98:89:c4:ce:85:55:12:
aa:95:a1:da:07:96:d9:93:1d:35:a9:bd:92:0f:22:
7a:a1:0c:af:1c:eb:85:68:f2:4c:43:f6:5c:b6:c9:
cf:31:ca:cc:4d:a1:3f:79:0c:b9:95:c2:dc:b6:21:
39:d3:d8:09:4b:36:73:de:19:c2:5f:65:b3:23:dc:
fe:29:ea:2c:ee:2f:f0:ad:b8:15:1e:dc:f4:bc:e6:
61:bc:de:3e:bc:42:7d:98:27:29:e4:86:2c:c2:e4:
72:c1
Exponent: 65537 (0x10001)
Attributes:
challengePassword        :unable to print attribute
Signature Algorithm: sha1WithRSAEncryption
cf:31:ca:30:fa:9f:a3:14:54:71:8e:50:28:f6:78:9d:11:84:
74:05:d2:da:59:68:91:8a:8b:90:83:53:37:92:22:59:3a:6e:
77:e7:65:f8:17:08:f0:8a:f4:b9:46:24:de:a9:fb:da:e2:71:
28:2c:77:3b:b0:00:fa:ac:b4:e5:43:d2:ad:98:df:14:84:c5:
24:43:f2:7d:0e:03:90:42:c8:40:69:82:78:01:a8:57:8a:fc:
f0:ed:94:a1:5c:a4:4a:1d:eb:79:6d:8b:0c:96:2f:05:43:70:
15:73:b9:30:d2:b1:b9:86:1d:85:5a:a5:63:08:02:55:60:c0:
6b:b1:82:40:70:b3:71:7a:0f:5a:77:b0:de:eb:23:62:8a:5b:
d7:8c:d9:34:ad:01:a3:cd:96:cf:92:df:59:5e:c8:5c:3a:aa:
42:79:0a:59:5b:d3:73:98:e5:77:2c:e0:27:21:5c:65:5a:e2:
ad:12:f4:d5:53:9e:fa:32:9e:bf:28:b0:02:4d:35:93:96:3e:
20:49:2c:2f:38:e9:3f:b9:43:c1:52:93:25:aa:82:8e:66:d0:
ff:8e:70:0c:63:bb:d2:06:c0:e1:e7:a9:6f:18:15:ed:9a:81:
9e:a4:0c:35:53:f2:e5:83:de:a0:33:3f:87:1a:12:fb:63:8f:
c5:a7:ea:9a

6. Symantic will email you the trial certificate
7. How to install on EC2 load balancer
Go to ec2 instance and select the correct load balancer 
Select listners
Add a new/edit HTTPs load balanccer and add the certificate in SSL certificate colomn
Select Upload a new SSL Certificate and give the followings Certificate Name, Private Key and Public Key Certificate and save it
Done
8.Now you should be able to access your site on https:// without any issue

Friday, September 27, 2013

Architecting with AWS Melbourne





It was extremely good training for architecture on Amazon Web Services Cloud.

Areas covered

  • Basic overview
  • S3
  • Cloud Front
  • EC2
  • EBS
  • RDS
  • Route 53
  • VPC, Subnets
  • IMA
  • Costing
  • Reference Architectures
  • Challenges
  • Case study

Paypal with Ruby 2.0 and Active Merchant



 This can be use with Ruby 2.0 or if your using for ecommerce application with rails 4.0 and it is tested with active merchant 1.29.3

1. Install active merchant
     gem install activemerchant

2. Create paypal sandbox account with business pro
3. Create a Ruby file

require "rubygems"
require "active_merchant"

ActiveMerchant::Billing::Base.mode = :test

gateway = ActiveMerchant::Billing::PaypalGateway.new(
  :login => "dwwwrwrutest1_api1.gmail.com",
  :password => "1380282787",
  :signature => "AscqxJyW-0NJcj5gJYTIXmFahhqQAtMS8.MCcHIHTVA26-3A76p.ctmP"
)

credit_card = ActiveMerchant::Billing::CreditCard.new(
  :brand              => "Visa",
  :number             => "5024007148673554",
  :verification_value => "123",
  :month              => 1,
  :year               => Time.now.year+1,
  :first_name         => "Boundry",
  :last_name          => "Unlimited"



if credit_card.valid?
  # or gateway.purchase to do both authorize and capture
  response = gateway.authorize(1200, credit_card, :ip => "127.0.0.1", :currency => "AUD", :customer => "Test Name", :email =>"suaua@hhdd.com")
  if response.success?
    gateway.capture(1200, response.authorization)
    puts "Purchase complete!"
  else
    puts "Error: #{response.message}"
  end
else
  puts "Error: credit card is not valid. #{credit_card.errors.full_messages.join('. ')}"
end

4.Run >ruby filename.rb
5. This example is extracted from Railscasts and can be useful to play around with different Paypal features

Wednesday, September 25, 2013

Configure SSL for Single instance Tomcat in AWS


How to configure SSL for Single instance Apchae Tomcat in AWS environment


1. Create private key using open SSL
   >openssl genrsa 1024 > privatekey.pem
2. Create a certificate signing requests
   >openssl req -new -key privatekey.pem -out csr.pem

Normally, you would submit your CSR to a Certificate Authority (CA) to apply for a digital server certificate. 

However, you can also generate a self-signed certificate for testing purposes only. 

3. How to generate self signed certificate
>openssl x509 -req -days 365 -in csr.pem -signkey privatekey.pem -out server.crt

4. In you jee application create a folder name  .ebextensions in \src\main\resources
5. Create a file name 01run.config under the new directory and add the following code

   Resources: 
    mySecurityGroup: 
      Type: "AWS::EC2::SecurityGroupIngress"
      Properties: 
        GroupName: 
          Ref: "AWSEBSecurityGroup"
        IpProtocol: "tcp"
        FromPort: "443"
        ToPort: "443"
        CidrIp: "0.0.0.0/0"

5. Build and create your new .war file
6. Login to your EC2 instance using PuTTy as root user and install mod_ssl using yum
            yum install mod_ssl
7.Creates(if not exsists) an ssl.conf file in your /etc/httpd/conf.d/ directory and add/modify the following details


mode: 000777
    owner: ec2-user
    group: ec2-user
    content: |
      LoadModule ssl_module modules/mod_ssl.so
      Listen 443
      <VirtualHost *:443>
        <Proxy *>
        Order deny,allow
        Allow from all
        </Proxy>
        SSLEngine on
        SSLCertificateFile "/tmp/server.crt"
        SSLCertificateKeyFile "/tmp/private.key"
        
        ProxyPass / http://localhost:8080/ retry=0
        ProxyPassReverse / http://localhost:8080/
        ProxyPreserveHost on
        
        LogFormat "%h (%{X-Forwarded-For}i) %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""
        ErrorLog /var/log/httpd/elasticbeanstalk-error_log
        TransferLog /var/log/httpd/elasticbeanstalk-access_log

      </VirtualHost>

8.Copy the generated private key and certificate to /tmp in EC2
9. Following commands will be useful to handle any issues 

rm -f  /var/lock/subsys/httpd
sudo netstat -ltnp | grep ':80'

sudo kill -9 xxxx
fuser -k -n tcp 80

service httpd restart

Sunday, July 28, 2013

Upload java script files to Amazon S3 using Ruby

require "s3"
service = S3::Service.new(:access_key_id => "KEY.................",
                          :secret_access_key => "SECRET ACCESS KEY....................")

bucket = service.buckets.find("s3 bucket name")

new_object = bucket.objects.build("s3 object location")
new_object.content = open(s3 object name)
new_object.content_type = "application/x-javascript"
new_object.cache_control = "max-age=604800"
new_object.content_encoding = "gzip"
new_object.save

Store OAuth 10a token in the database

1. Create a token table as below
 This is how you do in mysql
CREATE TABLE `token` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `consumer_id` int(10) NOT NULL,
 `public_key` varchar(255) DEFAULT NULL,
 `private_key` varchar(255) DEFAULT NULL,
 `created_date` timestamp NULL DEFAULT NULL,
 `callback_url` varchar(255) DEFAULT NULL,
 `verifier` varchar(255) DEFAULT NULL,
 `access_token` int(2) DEFAULT NULL,
 `authentication` blob,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2. Write a custom JDBC token service class
public class CustomTokenService {
private TokenDao tokenDao;

public CustomTokenService(TokenDao tokenDao) {
this.tokenDao = tokenDao;
}

public OAuthProviderTokenImpl readToken(String token) {
List<Token> sessionList = tokenDao.getNamedQueryAndNamedParam("Token.findById", "id", token);
Token session = sessionList.get(0);
for (Token t : sessionList) {
if (t.getIsActive() == 1) {
session = t;
}
}
session.setLastAccessedDate(new Date());
tokenDao.saveOrUpdate(session);
OAuthProviderTokenImpl accessToken = createOAuthProviderToken(session);
return accessToken;
}

public void storeToken(String tokenValue, OAuthProviderTokenImpl token) {         // Token class is orm of token table
Token customToken = new Token();
customToken.setCreatedDate(new Date());

Authentication userAuthentication = token.getUserAuthentication();
if (userAuthentication != null) {
byte[] authSerialized = serializeAuthentication(userAuthentication);
customToken.setUserAuthentication(authSerialized);
}

String consumerKey = token.getConsumerKey();
// need to create a consumer object
customToken.setConsumerId(consumer);
customToken.setSessionId(token.getValue());
String callbackUrl = token.getCallbackUrl();
String verifier = token.getVerifier();
customToken.setCallbackUrl(callbackUrl);
customToken.setVerifier(verifier);
customToken.setPrivateKey(token.getSecret());
customToken.setPublicKey(token.getValue());

Integer accessToken = token.isAccessToken() ? 1 : 0;
customToken.setAccessToken(accessToken);
tokenDao.saveOrUpdate(customToken);
}

public OAuthProviderTokenImpl removeToken(String tokenValue) {
// remove or null from the database and return the object
tokenDao.saveOrUpdate(token);
OAuthProviderTokenImpl tokenImpl = createOAuthProviderToken(token);
return tokenImpl;
}

private OAuthProviderTokenImpl createOAuthProviderToken(Token findById) {
OAuthProviderTokenImpl token = new OAuthProviderTokenImpl();
if (findById.getUserAuthentication() != null) {
Authentication userAuthentication = deserializeAuthentication(findById
.getUserAuthentication());
token.setUserAuthentication(userAuthentication);
}
//create the consumer key
token.setConsumerKey(consumerKey);
boolean accessToken = false;
if (findById.getAccessToken() == 1) {
accessToken = true;
}
token.setAccessToken(accessToken);
token.setSecret(findById.getPrivateKey());
token.setValue(findById.getPublicKey());
token.setCallbackUrl(findById.getCallbackUrl());
token.setVerifier(findById.getVerifier());
return token;
}

protected String extractTokenKey(String value) {
if (value == null) {
return null;
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(
"MD5 algorithm not available.  Fatal (should be in the JDK).");
}

try {
byte[] bytes = digest.digest(value.getBytes("UTF-8"));
return String.format("%032x", new BigInteger(1, bytes));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(
"UTF-8 encoding not available.  Fatal (should be in the JDK).");
}
}

protected byte[] serializeAuthentication(Authentication authentication) {
return SerializationUtils.serialize(authentication);
}

protected Authentication deserializeAuthentication(byte[] authentication) {
return (Authentication) SerializationUtils.deserialize(authentication);
}
}

3. Write Custom OAuth Token Service
public class CustomOAuthTokenService extends RandomValueProviderTokenServices{

CustomTokenService customTokenService;
protected final ConcurrentHashMap<String, OAuthProviderTokenImpl> tokenStore = new ConcurrentHashMap<String, OAuthProviderTokenImpl>();

public CustomOAuthTokenService(CustomTokenService customTokenService) {
super();
this.customTokenService = customTokenService;
}

@Override
protected OAuthProviderTokenImpl readToken(String token) {
OAuthProviderTokenImpl readToken = customTokenService.readToken(token);
return readToken;
}

@Override
protected void storeToken(String tokenValue, OAuthProviderTokenImpl token) {
customTokenService.storeToken(tokenValue, token);
}

@Override
protected OAuthProviderTokenImpl removeToken(String tokenValue) {
return customTokenService.removeToken(tokenValue);
}

}

4. Changes to Spring security config file

<beans:bean id="tokenServices" class="....CustomOAuthTokenService">
<beans:constructor-arg ref="customTokenService" />
</beans:bean>

<beans:bean id="customTokenService" class=".....CustomTokenService">
<beans:constructor-arg>
<beans:ref bean="tokenDao" />
</beans:constructor-arg>
</beans:bean>

Permission based authorization with OAuth 10a

OAuth 10a deals with roal based authorization. 
Can we do the permission based authorization with oauth 10a ?

That is can we authorize a URL pattern, can we authorize frequency of request URL 
Or can we authorize particulate client IP to access the resource

The easiest way is to write a custom expression voter as below

public class CExpressionVoter implements AccessDecisionVoter<FilterInvocation> {
    public int vote(Authentication authentication, FilterInvocation fi, Collection<ConfigAttribute> attributes) {
        assert authentication != null;
        assert fi != null;
        assert attributes != null;

        if(authentication.getPrincipal()!=null ) {
        Object principal = authentication.getPrincipal();
        if(principal instanceof UserDetails) {
        UserDetails userDetails = (UserDetails)principal;
        if(userDetails.getUsername().equalsIgnoreCase("anonymousUser")){
        return -1;
        } else {
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
          int i = -1;
        for (GrantedAuthority grantedAuthority : authorities) {
String uriAuthorityPattern = grantedAuthority.getAuthority().toLowerCase();
String uriRequest = fi.getRequestUrl().toLowerCase();
String fullRequestUrl = fi.getFullRequestUrl();

String delimiters = "/\\s*|\\?\\s*";
String[] uriPatternArray = uriRequest.split(delimiters);
String uriPattern = null;
if(uriPatternArray !=null & uriPatternArray.length >=2) {
uriPattern = uriPatternArray[1];
}
// This is the sample to check the URL pattern. Likewise you can do other authentications, All the autorities can be loaded to
// user detail object using a custom user detail service, sample given below
if (uriPattern!=null & uriPattern.equalsIgnoreCase(uriAuthorityPattern)){
i = 1; break;
} else {
i = -1;
}
}
        return i;        
        }
       
        if (principal instanceof String) {
        if(((String) principal).equalsIgnoreCase("anonymousUser")){
        return -1;
        }
        }
        }
        return 1;
    }
    public boolean supports(ConfigAttribute attribute) {
    return true;
    }

    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(FilterInvocation.class);
    }
}

Custom User Detail Service
public class CUserDetailService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ArrayList<String> authority  = new ArrayList<String>();
// Get the values from the database and add as arrayList
UserDetails result = new CustomUserDetails(findById, authority);
return result;
}

}

Custom User Details

public class CustomUserDetails implements UserDetails {
private String userName;
private String password;
private Collection<GrantedAuthority> grantedAuthorities;

public CustomUserDetails(CustomUser user, List<String> authority){
this.grantedAuthorities = new ArrayList<GrantedAuthority>();
for (String p : authority) {
GrantedAuthority ga = new SimpleGrantedAuthority(p);
this.grantedAuthorities.add(ga);
}
}

public Collection<? extends GrantedAuthority> getAuthorities() {
return this.grantedAuthorities;
}

// write inherited methods for UserDetails
}

Custom Secure Resource Filter
// this is a dummy implementation
public class CSecureResourceFilter implements FilterInvocationSecurityMetadataSource {
public Collection<ConfigAttribute> getAllConfigAttributes() {
StringBuilder rolesStringBuilder = new StringBuilder();
rolesStringBuilder.append("USER1");
List<ConfigAttribute> createListFromCommaDelimitedString = SecurityConfig.createListFromCommaDelimitedString(rolesStringBuilder.toString());
return createListFromCommaDelimitedString;
}

public Collection<ConfigAttribute> getAttributes(Object filter) throws IllegalArgumentException {
StringBuilder rolesStringBuilder = new StringBuilder();
rolesStringBuilder.append("USER1");
return SecurityConfig.createListFromCommaDelimitedString(rolesStringBuilder.toString());
}
public boolean supports(Class<?> arg0) {
return true;
}
}


Spring security configuration file

..

<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:constructor-arg name="decisionVoters">
<beans:list>
<beans:bean class="..................CExpressionVoter" />
</beans:list>
</beans:constructor-arg> 
</beans:bean>

<http use-expressions="true" auto-config='true' access-denied-page="/login.jsp" > 
<form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp" login-processing-url="/login.do" />
<custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="filterSecurityInterceptor" /> 
</http> 

<beans:bean id="customUserDetailService" class=".....CUserDetailService" /> 

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailService"/> 
</authentication-manager>

<beans:bean id="customSecureResourceFilter" class=".......CSecureResourceFilter"/>


<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="accessDecisionManager" ref="accessDecisionManager"/>
<beans:property name="securityMetadataSource" ref="customSecureResourceFilter"/>

</beans:bean>