Sunday, October 25, 2015

JDBC Connection Pooling

In general pooling is suitable for any expensive limited resource. What about database connections ? 

  1. Establishing new database is time consuming

  2. Utilize network infrastructure

  3. Initializing a database connection session in the back end database

  4. perform user authentication and many more 

     

So it is reasonable to have valuable database connection in a pool.

 

sample source code to get a connection from connection pool

try {
           Connection dbConnection = dataSource.getConnection();
           dbConnection.setAutoCommit(false);
           dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
           return dbConnection;
       } catch (SQLException e) {
           String errMsg = "Error when getting a database connection object from the Identity data source.";
}


Why you should close database connection once operation is done ?
Yeah….! from common sense we know after closing database connection it will return back to the connection pool and so that others can use it. If you didn’t close it waste of valuable resource. 

Let’s think bit more deep 

try {
connection = dataSource.getConnection();
} finally {
connection.close();
}

What is wrong here ..? what happen dataSource.getConnection() throws an exception and connection assign to null and you are getting NPE instead of SQLException
OK……. but simple null check would do the job

Now you have to close statement too…

try {
connection = dataSource.getConnection();
statement=connection.createStatement();
} finally {
if (statement != null) statement.close();
if (connection != null) connection.close();
}

What if statement.close() throws an exception ?
Now it is being get complicated with different combinations.
See this Util method structure

    public static void closeAllConnections(Connection dbConnection, ResultSet rs, PreparedStatement prepStmt) {

           closeResultSet(rs);
           closeStatement(prepStmt);
           closeConnection(dbConnection);
    }

    public static void closeConnection(Connection dbConnection) {
           if (dbConnection != null) {
                   try {
                           dbConnection.close();
                   } catch (SQLException e) {
                           log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e);
                   }
           }
    }

    public static void closeResultSet(ResultSet rs) {
           if (rs != null) {
                   try {
                           rs.close();
                   } catch (SQLException e) {
                           log.error("Database error. Could not close result set  - " + e.getMessage(), e);
                   }
           }
    }

    public static void closeStatement(PreparedStatement preparedStatement) {
       if (preparedStatement != null) {
           try {
               preparedStatement.close();
           } catch (SQLException e) {
               log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e);
           }
       }

    }

Common mistake could happen with prepared statement
  1. Never dereference prepared statement    
prepStmt = conn.prepareStatement(sqlStmt1);
//do some stuff
    prepStmt = conn.prepareStatement(sqlStmt2);
missed reference to prepared statement  

  1. Use prepStmt.clearParameters() to clear all parameters if you want to execute same prepared statement with different set of parameters

  1. Use prepStmt.clearBatch() to clear all batch entries

Sunday, March 29, 2015

Principle behind RSA Private Key / Public Key

 Step 01:

Select two large random prime numbers. Let’s take some small numbers p=11 and q=5 to understand the concept

Calculate RSA modulus by multiplying together

n = p.q
  = 11.5
  = 55


 Step 02:

Calculate the totient of RSA modules

@(n) = (p-1)(q-1)   
     = 10.4
     = 40

Step 03:

Select a number that is relatively prime to the totient 1 < e < @(n)

3, 7 , 9 , 11 , 13 ,….

e = 7

Step 04:

Find the modular inverse of e with respect to @(n)

call d it will be a part of private key

e*d mod @(n) = 1

7* d mod 40 = 1

solve for d with extended Euclidean algorithm

part 01: Euclidean algorithm

40x + 7y = 1
40 =  5(7) + 5
7 =  1(5) + 2
5 =  2(2) + 1

part 02: Back substitution

1 = 5 -2(2)
1 = 5 -2(7 -5)
1= 3(5) -2(7)
1= 3(40 - 5.7) -2(7)
1= 3(40) - 17(7)

Since the number in front of 7 is negative

let's take d = 40 - 17 = 23

Private key (23, 55)

Public key (7, 55)

Saturday, March 21, 2015

SAML SSO for Salesforce using WSO2 Identity Server 5.0.0

WSO2 Identity server can be configured as an Identity Provider for Salesforce. In that case Salesforce will be a service provider and you can utilize the account reside inside the Identity Server in order to authenticate with Salesforce.

Step - 01: Configure Salesforce
a. Create an account in http://developer.force.com/ if you already don’t have a account.
b. Go to force.com and login to the above created account and go to Home > Domain Management > My Domain  and create new domain

SalesForce takes some time to register the domain.

Go to Home > Security Controls > Single Sign­On Settings  

Click Edit from Single Sign On settings 

Screen Shot 2015-03-22 at 12.09.16 AM.png 

Enable SAML

Screen Shot 2015-03-22 at 12.07.44 AM.png  
 c. Click on new and configure other properties as given below. You can use this command to export certificate from wso2carbon.jks

keytool -export -keystore wso2carbon.jks -alias wso2carbon -file wso2.crt -­storepass wso2carbon

Screen Shot 2015-03-21 at 11.26.32 PM.png
  

Name
SSO


SAML Version
2.0
Issuer



API Name

Entity Id
(Issuer of SAML response send from Identity Server to salesforce)

SSO

(Issuer of SAML Request send from salesforce to Identity Server)


Identity Provider Certificate
CN=localhost, O=WSO2, L=Mountain View, ST=CA, C=US
Expiration: 13 Feb 2035 07:02:26 GMT
(upload wso2.cert exported from wso2carbon.jks)
Request Signing Certificate
Default Certificate
Request Signature Method
RSA-SHA1
Assertion Decryption Certificate
Assertion not encrypted
SAML Identity Type
Username
SAML Identity Location
Subject
Identity Provider Login URL
https://localhost:9443/samlsso
Identity Provider Logout URL
https://localhost:9443/samlsso
Custom Error URL
Service Provider Initiated Request Binding

HTTP POST
d. Goto Home > Domain Management > My Domain.

Click on deploy to users

from Authentication Configuration select SSO

Screen Shot 2015-03-22 at 12.40.48 AM.png 
e. from My Domain Settings tick Prevent login from https://login.salesforce.com 

Screen Shot 2015-03-22 at 12.41.14 AM.png

f. Create a new user in Salesforce. General Information is enough.


Login to force.com with the initially created account and go to Home > Manage Users > Users and create a New User with email username format (nuwan@wso2.com).

Step - 02: Configure WSO2 Identity Server
 
a. Please follow these steps before starting Identity Server because you need to create users with email username format in Identity Server.

i. Open carbon.xml in IS_HOME/repository/conf and uncomment 
<EnableEmailUserName>true</EnableEmailUserName>

ii. Open usermgt.xml IS_HOME/repository/conf and add the following property under the ReadWriteLDAPUserStoreManager 

<Property name="UsernameWithEmailJavaScriptRegEx">[a­zA­Z0­9@._­|//]{3,30}$</Property>



Start the Identity Server and create a user in Identity Server with ‘Login’ permission.  Salesforce accepts usernames in email format and therefore Identity Server user should have a username in email format like nuwan@wso2.com.

b. Add new service provider Service Provider > Add

Screen Shot 2015-03-22 at 12.56.44 AM.png

c. Configure SAML2 Web SSO Configuration



Issuer                                        https://saml.salesforce.com
Assertion Consumer URL            Use the Salesforce Login URL (found under SSO settings in Salseforce).      Eg :
https://gayang-dev-ed.my.salesforce.com?so=00D28000000JPTA
 
d. Change the issuer of Resident Identity Provider from Identity Server 

Resident Identity Provider > Inbound Authentication Configuration > SAML2 Web SSO Configuration 

change Identity Provider Entity id : https://localhost:9443/samlsso


  Step - 03: Test Salesforce SSO with WSO2 Identity Server

Access your domain in salesforce using the Salesforce Login URL like https://gayang-dev-ed.my.salesforce.com?so=00D28000000JPTA. You will be redirected to WSO2 Identity Server Login page.

Login with credentials of the newly created user (nuwan@wso2.com) . Now you will get redirected back to salesforce home page of that user.