Tuesday, October 6, 2015

Java Regex


Putting this up for my own reference more than any other reason. Java Regex are useful in manipulation strings. A regex consist of pattern blocks and optional quantifiers.


Pattern Blocks


some patterns are built in to java,

\d - digit
\w – word character
\s – whitespace

if a range of characters need to be used as a pattern it should be put as follows,

[a-z] – a to z simple
[a-zA-Z] - a to z capital and simple
[1-9] – 1 to 9

Quantifiers


these add meaning to the patterns. They should be added immediately after the pattern.

* - match pattern 0 or more times
+ - match pattern 1 or more times
{n} - match pattern exactly n times
{n,m} – match pattern between n to m times


Regex Examples


[a-zA-Z]* - a to z capital and simple 0 or more times
[a-zA-Z]+ - a to z capital and simple 1 or more times
\d{2,5} – digits 2 to 5 times
[.]*[a-zA-Z]{1,5} - . 0 or more times in the beginning followed by a to z capital and simple 1 to 5 time, the whole pattern once. 

Thursday, September 10, 2015

How to Write a Simple Authentication Handler for an API in WSO2 ESB

whats covered: creating a simple authentication handler for an API in WSO2 ESB 4.8.1


1) Create the Project


Generate the pom file with the required dependencies using WSO2 Developer Studio.


2) Put in the Authentication Logic


In this example the authentication is done based on a per-configured header value in the API request. Find the complete code here[1].

Put the authentication logic inside the handleRequest() method.

....
....

boolean auticationSuccessfull;
        if(!headers.containsKey(TOKEN_HEADER_NAME))
        {
            throw new SynapseException("Access token was not found in the header");
        }
        else
        {
            String token = headers.get(TOKEN_HEADER_NAME).toString();
            if(authenticate(token))
            {
                auticationSuccessfull=true;
            }
            else
            {
                auticationSuccessfull=false;
            }
        }

return auticationSuccessfull;

....
....

private boolean authenticate(String tk)
    {
        //authentication logic
        boolean sentinal=false;
        if(tk.equals("testtoken"))
        {
            sentinal=true;
        }
        if(!sentinal)
        {   
            log.debug("authentication failed for token: "+tk);   
        }
        return sentinal;
    }

....
....


3) Build and Copy the Jar


Drop the jar inside <ESB_HOME>/repository/components/lib


4) Include Handler in the API Configuration


Open up the API configuration with an editor(find it in <ESB_HOME>/repository/deployment/server/synapse-configs/default/api/), Include the handler after the API resource closing tag(at the end of the config) as shown below,

....
....

   </resource>
   <handlers>
      <handler class="com.dumiduh.SimpleAuthenticationHandler"/>
   </handlers>
</api>


[1] - https://drive.google.com/file/d/0B9oVIeyHJKBXY1hZZjBvT1FGQlU/view?usp=sharing

Tuesday, September 8, 2015

Another Way to Transfer Files Over the Network in Linux


Transfer files with nc when SimpleHTTPServer python module is not available.

nc -l <port_to_listen_on> < <file to transfer>

nc <ip_of_server> <port> > <output_file_name>


example,

nc -l 9000 < logs.zip
nc 192.168.1.3 > logs.zip

Saturday, August 29, 2015

How to Invoke a Shell Script using WSO2 ESB


whats covered: creating a custom mediator to invoke shell scripts for ESB 4.8.1.


1) Create a Mediator Project


Generate a mediator project using WSO2 Developer Studio. Developer Studio Dashboard > Mediator Project.


2) Put in the logic to execute shell scripts


exec() method of the of the current runtime object can be used for this purpose. put the logic inside the mediate method(this method should return true to continue the mediation flow). Find the complete code here[1]


    ...
    ...   
    public String execute()
    {
        StringBuilder output = new StringBuilder();
        Process p;
        try
        {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }

        return output.toString();
    }
    ...
    ...


3) Build and Copy the jar

build the project. Copy the created jar file to <ESB_HOME>/repository/components/lib .


4) Create a proxy service

create a proxy service with the class mediator in the mediation path.

...
...
<inSequence>
<class name="org.wso2.demo.ShellScriptMediator">
      <property name="scriptname"
                value="/home/dumiduh/backup_script.sh"/>
      <property name="scriptparam"
                value="/home/dumiduh/BACKUPS"/>
</class>
<drop/>
</inSequence>
...
...


[1] - https://github.com/handakumbura/ShellScriptMediatorDemo/tree/master

Find more info on the class mediator here,
https://docs.wso2.com/display/ESB481/Class+Mediator


Friday, August 28, 2015

How to Run WSO2 BAM 2.5.0 on Cygwin


whats covered: configuring and running BAM 2.5.0 on Win 7 over Cygwin.

1) Install Java


install java using the installer and once thats complete setup JAVA_HOME user variable and add the java bin folder to path system variable.


2) Install Cygwin


download from https://cygwin.com/install.html and install using the wizard.


3) Setup JAVA_HOME in Cygwin.


Open <cygwin_home>/home/<user_name>/.profile and export JAVA_HOME following way,

/cygdrive/c/<java_home_user_variable_in_windows>

ex,

export JAVA_HOME=/cygdrive/c/Java/jdk1.7.0_45


4) Run the Start Script


open cygwin terminal, navigate to BAM 2.5.0 folder and start the server with wso2server.sh script. 




Thursday, February 26, 2015

Building WSO2 ESB 4.8.0 from Source


1) create the folders

create folder structure

|---carbon
    |---orbit
    |---kernel
    |---platfrom

orbit contains 3rd party components required by wso2 products, kernal contains the carbon core dependencies required for wso2 products and platform contains the product components them self.




2) checkout source

 

move into orbit and checkout http://svn.wso2.org/repos/wso2/carbon/orbit/trunk/
move into kernel and checkout http://svn.wso2.org/repos/wso2/carbon/kernel/branches/4.2.0/
move into platfrom and checkout http://svn.wso2.org/repos/wso2/carbon/platform/branches/turing/



3) build 

 

build orbit and kernal by moving to the respective folders and keying
mvn clean install -Dmaven.test.skip=true
Since we need to only build ESB open up the pom.xml in platfrom/turing and comment out <module>products</module> and run maven install command(as above).

Move into platfrom/turing/products/esb/4.8.0 and run maven install command.

find the built esb pack in platform/turing/products/esb/4.8.0/modules/distribution/target


Please note that jdk 1.6 is required to build wso2 products.

Wednesday, January 14, 2015

How to Configure Identity Server SSO Sample for Tenants

whats covered: configuring the SSO sample app with Identity Server 5.

1) download and build the app

checkout and build the app. copy war to tomcat(there is a compatibility issue between some jars used in travelocity app and Application Server)


svn co http://svn.wso2.org/repos/wso2/carbon/platform/branches/turing/products/is/5.0.0/modules/samples/sso/


2) exchange keys between app and IS


when encryption is enabled, the saml requests and responses are encrypted using the relevant parties private keys. In-order to decrypt these messages on the other end the two parties must have each others public keys.

The default key store of the travelocity app can be found in WEB-INF/classes, extract the public certificate associated with the private key used in the app as shown below,

keytool -export -alias wso2carbon -file <name_for_public_key> -keystore wso2carbon.jks

import this key to the tenants keystore using the key management feature(configure > keystores)

export the public key of the tenant using the key management feature.

import the download certificate of the tenant to the travelocitys keystore as shown below,
 

keystore -import -file <name of the tenants public cert> -alias <give alias to cert> -keystore wso2carbon  


3) configure SSO on the app side


modify travelocity.com/WEB-INF/classes/travelocity.property as follows,

SAML.IssuerID=travelocity.com@<tenant domain>

SAML.EnableResponseSigning=true

SAML.EnableAssertionSigning=true

SAML.EnableAssertionEncryption=true

SAML.EnableRequestSigning=true

SAML.IdPCertAlias=<alias of the tenant public key>  


4) register service provider in IS


register a service provider(main > identity > service providers > add) by giving a service provider name(e.g. TravelocityApp) and clicking register.

in the proceeding screen, expand inbound authentication > SAML 2 SSO Configuration and click on configure. configure SAML SSO for the service provider as shown below,


Issuer :  IssuerID found in the travelocity.properties file, minus the tenant domain

Assertion Consumer URL : the URL the Identity Server will send the SAML Response, find this URL in the travelocity.properties file.

Use fully qualified username in the NameID : enabled

Enable Response Signing : enabled

Enable Assertion Signing : enabled

Enable Signature Validation in Authentication Requests and Logout Requests : enabled

Enable Assertion Encryption : enabled

Select the public key of the travelocity app from the drop-down.




Thats it. Login with a user in the tenant used for service provider registration.  


common issues 

having conflicting configurations between the SP registered and the app. e.g. Single Logout(SLO) being enabled on application side while in SP registration it being disabled. 

not providing tenant domain with issue id on application side.