Saturday, March 17, 2018

Laravel - Setup Tips


Valet

HTTP request sent, awaiting response... Read error (Connection reset by peer) in headers:
To resolve this error, do the following:
1. valet stop
2. valet uninstall
3. rm -rf ~/.valet
4. valet install
5. valet start
6. Link the applications again.


Restart phpfpm on homestead:
sudo nginx -s reload
sudo service php7.0-fpm restart

Laravel - Code Tips

To Log all queries executed by Eloquent:
Add the below code snippet into AppServiceProvider boot() method.

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
            \Illuminate\Support\Facades\Log::info($query->sql);
            \Illuminate\Support\Facades\Log::info($query->bindings);
            \Illuminate\Support\Facades\Log::info($query->time);
        });

\DB::listen(function($sql, $bindings, $time) {
            Log::info($sql);
            Log::info($bindings);
            Log::info($time);
        });



Wednesday, March 8, 2017

AWS

EC2:
Login:
1. Copy your .pem file to ~/.ssh.
2. Change permissions to chmod 500 <your_file>.pem
3. Login to your server.

ssh -i /full-path-to/.pem ec2-user@PUBLIC_DNS


INSTALL PHP:
sudo yum install php56

Free Memory Check:
free -m (in MB)

Hard disk capacity Check:
df -h (Human Readable)

GIT Resets


GIT REST HELP
  • Soft
    • git reset --soft <commit id>
  • Mixed
    • git reset --mixed <commit id>
  • Hard
    • git reset --hard <commit id>

Check git log status:
git log --oneline

Soft:
git reset --soft <commit id>

Result:
Brings the files changed after this commit id into staging index. 
i.e, as if those changed files were added using git add command.

Mixed:
git reset --mixed <commit id>

Result:
Brings the files changed after this commit id into Working Directory. 
i.e, as if those changed files were changed but not gone through git add yet.

Hard:
git reset --hard <commit id>

This is the most dangerous command as it is going to completely wipe out our working directory and staging index. Any files you were tinkering with will be gone.

Result:
Brings the files changed after this commit id into staging index. 
i.e, as if those changed files were added using git add command.


git reset --hard HEAD
This will bring your code base to the commit where HEAD is pointing to.
Basically this will wipe out any changes in Working Directory and Staging Index.


TODO:
Pushing reset commit to remote?

Friday, January 20, 2017

Set Mule ESB to use TLS v1.2

Mulesoft Anypoint Studio was giving me trouble for a long time to connect to an external HTTP server that supports only TLSv1.2.

Below options did not work for me:
-Dhttps.protocols=TLSv1.2
-Djdk.tls.client.protocols=TLSv1.2

Solution:
I had to create a tls-default.conf file directly under src/main/resources (classpath root folder) and set

enabledProtocols=TLSv1.2


Full Configuration:
# This file allows to restrict SSL behavior in Mule. If the file doesn't exist or a property is not defined,
# default values of the current security provider will be used.


# Cipher suites that will be enabled in SSL. If this property is set, SSL sockets will
# only use cipher suites that are provided in this list and supported by the current security provider.
#enabledCipherSuites=TLS_KRB5_WITH_3DES_EDE_CBC_MD5,        \
#                    SSL_DH_anon_WITH_DES_CBC_SHA,          \
#                    TLS_DH_anon_WITH_AES_128_CBC_SHA,      \
#                    TLS_DHE_RSA_WITH_AES_128_CBC_SHA,      \
#                    SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, \
#                    SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,     \
#                    TLS_DHE_RSA_WITH_AES_256_CBC_SHA,      \
#                    TLS_KRB5_WITH_3DES_EDE_CBC_SHA,        \
#                    TLS_KRB5_WITH_DES_CBC_MD5,             \
#                    TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5,   \
#                    SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, \
#                    SSL_DHE_DSS_WITH_DES_CBC_SHA,          \
#                    TLS_KRB5_WITH_DES_CBC_SHA,             \
#                    SSL_RSA_WITH_NULL_MD5,                 \
#                    TLS_DHE_DSS_WITH_AES_256_CBC_SHA,      \
#                    SSL_DH_anon_WITH_3DES_EDE_CBC_SHA,     \
#                    TLS_RSA_WITH_AES_128_CBC_SHA,          \
#                    SSL_DHE_RSA_WITH_DES_CBC_SHA,          \
#                    TLS_DH_anon_WITH_AES_256_CBC_SHA,      \
#                    TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA,   \
#                    SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA, \
#                    SSL_RSA_WITH_NULL_SHA,                 \
#                    TLS_RSA_WITH_AES_256_CBC_SHA,          \
#                    SSL_RSA_WITH_DES_CBC_SHA,              \
#                    TLS_EMPTY_RENEGOTIATION_INFO_SCSV,     \
#                    SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,     \
#                    TLS_DHE_DSS_WITH_AES_128_CBC_SHA,      \
#                    SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,     \
#                    SSL_RSA_WITH_3DES_EDE_CBC_SHA


# Protocols that will be enabled in SSL. If this property is set, SSL sockets will only use protocols
# that are provided in this list and supported by the current security provider.
#enabledProtocols=TLSv1,TLSv1.1,TLSv1.2
enabledProtocols=TLSv1.2

Monday, February 18, 2013

Custom XML Generator

This is a simple XML Generator that can be used to send in any object (tested with List and custom objects) and get the XML out of it. This could be useful while building java to xml transformations for any objects.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class XMLGeneratorImpl {

    public static final String GET_METHOD = "get";
    public static final String IS_METHOD = "is";
    public static final String EMPTY = "";
    public static final String START_TAG = "<";
    public static final String END_TAG = ">";
    public static final String SLASH = "/";

    private boolean trimPackageNames;

    private static final Set<Class> WRAPPER_TYPES = new HashSet(Arrays.asList(
            Boolean.class, Character.class, Byte.class, Short.class,
            Integer.class, Long.class, Float.class, Double.class, Void.class,
            String.class));

    private enum ObjectFormat {
        PRIMITIVE, OBJECT, LIST, MAP, SET, ARRAY;
    }

    public String toXML(Object input) {
        ObjectFormat format = getFormat(input);
        return convertToXml(input, format);
    }

    private String convertToXml(Object input, ObjectFormat format) {
        StringBuilder xml = new StringBuilder();
        String objectName = getObjectName(input);
        switch (format) {
        case OBJECT:
            xml.append(START_TAG).append(objectName).append(END_TAG);
            xml.append(getXMLFromObject(input));
            xml.append(START_TAG).append(SLASH).append(objectName)
                    .append(END_TAG);
            break;
        case ARRAY:
            xml.append(getXMLFromArray(input));
            break;
        case LIST:
            xml.append(getXMLFromList(input));
            break;
        case PRIMITIVE:
            xml.append(getXMLFromPrimitive(null, input));
            break;
        default:
            throw new IllegalArgumentException("Unsupported request object");
        }

        return xml.toString();
    }

    private String getXMLFromPrimitive(String key, Object input) {
        StringBuilder xml = new StringBuilder();
        String xmlTag = key == null ? getObjectName(input) : key;
        xml.append(START_TAG).append(xmlTag).append(END_TAG)
                .append(input.toString()).append(START_TAG).append(SLASH)
                .append(xmlTag).append(END_TAG);
        return xml.toString();
    }

    private String getXMLFromObject(Object input) {
        StringBuilder xml = new StringBuilder();
        List<Method> methods = getAllowedMethods(input);
        for (Method method : methods) {
            xml.append(getXMLValue(input, method));
        }
        return xml.toString();
    }

    private String getXMLFromArray(Object input) {
        StringBuilder xml = new StringBuilder();
        Object[] objects = (Object[]) input;
        for (Object object : objects) {
            ObjectFormat of = getFormat(object);
            xml.append(convertToXml(object, of));
        }
        return xml.toString();
    }

    private String getXMLFromList(Object input) {
        StringBuilder xml = new StringBuilder();
        List objects = (List) input;
        for (Object object : objects) {
            ObjectFormat of = getFormat(object);
            xml.append(convertToXml(object, of));
        }
        return xml.toString();
    }

    private List<Method> getAllowedMethods(Object input) {
        List<Method> getters = new ArrayList<Method>();
        Method[] methods = input.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (isGetterMethod(method)) {
                getters.add(method);
            }
        }
        return getters;
    }

    private boolean isGetterMethod(Method method) {
        boolean getter = false;
        if (method.getName().startsWith(GET_METHOD)
                || method.getName().startsWith(IS_METHOD)) {
            getter = true;
        }
        return getter;
    }

    private String getXMLValue(Object input, Method method) {
        StringBuilder xml = new StringBuilder();
        try {
            Object value = method.invoke(input, null);
            String xmlTagName = getObjectName(null, method);
            if (value != null) {
                ObjectFormat of = getFormat(value);
                switch (of) {
                case PRIMITIVE:
                    xml.append(START_TAG).append(xmlTagName).append(END_TAG)
                            .append(value).append(START_TAG).append(SLASH)
                            .append(xmlTagName).append(END_TAG);
                    break;
                case OBJECT:
                    xml.append(convertToXml(value, of));
                    break;
                case LIST:
                case MAP:
                case SET:
                case ARRAY:
                    xml.append(START_TAG).append(xmlTagName).append(END_TAG)
                            .append(convertToXml(value, of)).append(START_TAG)
                            .append(SLASH).append(xmlTagName).append(END_TAG);
                    break;
                }
            }
        } catch (IllegalArgumentException e) {
            // TODO: handle exception
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return xml.toString();
    }

    private ObjectFormat getFormat(Object input) {
        ObjectFormat format = ObjectFormat.OBJECT;
        Class clazz = input.getClass();
        if (isWrapperType(clazz)) {
            format = ObjectFormat.PRIMITIVE;
        } else if (clazz.getName().contains("List")) {
            format = ObjectFormat.LIST;
        }
        return format;
    }

    private boolean isWrapperType(Class clazz) {
        return WRAPPER_TYPES.contains(clazz);
    }

    private String getXMLTagName(Method method) {
        String xmlTagName = null;

        if (method.getName().startsWith(GET_METHOD)) {
            xmlTagName = method.getName().substring(3);
        } else {
            xmlTagName = method.getName().substring(2);
        }

        return xmlTagName;
    }

    public boolean isTrimPackageNames() {
        return trimPackageNames;
    }

    public void setTrimPackageNames(boolean trimPackageNames) {
        this.trimPackageNames = trimPackageNames;
    }

    private String getObjectName(Object input) {
        return getObjectName(input, null);
    }

    private String getObjectName(Object input, Method method) {
        String xmlTagName = EMPTY;
        if (input != null) {
            xmlTagName = input.getClass().getName();
            if (trimPackageNames && xmlTagName.indexOf(".") != -1) {
                xmlTagName = xmlTagName
                        .substring(xmlTagName.lastIndexOf(".") + 1);
            }
        } else if (method != null) {
            xmlTagName = getXMLTagName(method);
            if (trimPackageNames && xmlTagName.indexOf(".") != -1) {
                xmlTagName = xmlTagName
                        .substring(xmlTagName.lastIndexOf(".") + 1);
            }
        }
        return xmlTagName;
    }
} 

Saturday, February 9, 2013

@Controller and @RequestMapping

Since Spring 2.5 onwards, we can configure controllers through Spring Annotations which helps us in many ways.

  1. Spring bean definition files to be of minimal size.
  2. No need to extend any spring controllers and easy to create form and multi-action controller
@Controller:
Tells the spring framework that this class is used as a controller and should be considered by Dispatcher Servlet for delegating the requests to this controller.

@RequestMapping:
Tells the spring framework what are all the URLs that would be handled by this controller.

com.controller.test;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

@Controller("HelloWordController")

@RequestMapping("/hello")

public class HelloWorldController {

    @RequestMapping(value = "/world", method = RequestMethod.GET)

    public ModelAndView helloWord() {

        return new ModelAndView("HelloWorld");

    }

}

Now tell spring framework to scan your package for annotations. and define the HelloWorld webpage as per your requirement.

<context:component-scan base-package="com.controller.test" />

Thats it. Now deploy & start your application. Hit the below URL and see the actions.

http://localhost:8080/yourproject/hello/world

Sunday, February 3, 2013

Generating POJOs from Database Scema (Used HSQL)

Ok, Now in a project we have the tables created in a database server. How can i leverage those tables to generate my hibernate pojos or domain objects easily?

    
          a. Install Hibernate Tools.
          b. Go to Hibernate Perspective (Window -> Open Perspective -> Other -> Hibernate)
          c. In the Hibernate Configurations View, Right click -> Add Configuration
          d. Under Main Tab,
                * Select the project where the POJOS need to be generated.
                * Select the database connection as Hibernate Configured Connection.
                * Create the hibernate Configuration file (Properties file is not mandatory) with the following values.
                    <?xml version="1.0" encoding="UTF-8"?>
                    <!DOCTYPE hibernate-configuration PUBLIC
                            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
                    <hibernate-configuration>
                        <session-factory name="TechFes">
                            <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
                            <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:9001/TechFes</property>
                            <property name="hibernate.connection.username">SA</property>
                            <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
                        </session-factory>
                    </hibernate-configuration>
          e. Now go to Run icon (the run icon in Hibernate perspective) and click on Hibernate Code Generation Configurations.
          f. Under Main Tab,
                * Select the output directory where the files has to get generated.
                * Select the "Reverse Engineer from JDBC Connection" checkbox.
                            * Provide the package name under which the domain java objects need to be created.
                            * Uncheck "Detect many-to-many" associations. This will help in generating the pojo objects for the tables that are maintained only for many-many association.
          g. Under Exporters Tab,
                * Check the Domain Code, hibernate cfg file and if required annotations, etc.
               
          h. Click on Run and your domain code should have got generated.

Standalone HSQL DB Setup

I have a project and have the schemas available. But I don't have an actual database setup yet. Now run HSQLDB in standalone mode from command line and load the tables and get going :-) What are the steps to do that?

          a. Download latest version of HSQLDB from http://hsqldb.org.

          b. Goto hsql db folder and create a file named server.properties with the following entries.
                  server.database.0=file:hsqldb/TechFes
                server.dbname.0=TechFes
          c. Once the JAVA_HOME and PATH variables are updated with the correct java location,
               execute this command from hsqldb folder where server.properties file is created
                 
                  >java -classpath lib/hsqldb.jar org.hsqldb.server.Server
                 
               NOTE: This command would create a folder hsqldb and create the files for TechFes database under that folder.
             
          d. Now we need to open the database with additional params to the above command.
         
                >java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:hsqldb/TechFes --dbname.0 TechFes
               
             NOTE: This would open the database so clients can connect to it.
            
          e. Now we can use the below command to launch the UI for this database and make changes to the schema.
         
                >java -cp lib/hsqldb.jar org.hsqldb.util.DatabaseManagerSwing

Monday, May 21, 2012

Hibernate Connection Release Modes

Hibernate Connection Release Modes:

The different release modes that are supported by Hibernate are as follows:

1. on_close: The Hibernate session obtains a connection when it first needs to perform some JDBC access and maintains that connection until the session is closed.

2. after_transaction: uses ConnectionReleaseMode.AFTER_TRANSACTION. This setting should not be used in JTA environments. Also note that with ConnectionReleaseMode.AFTER_TRANSACTION, if a session is considered to be in auto-commit mode, connections will be released as if the release mode were AFTER_STATEMENT.

3. after_statement: uses ConnectionReleaseMode.AFTER_STATEMENT. Additionally, the configured ConnectionProvider is consulted to see if it supports this setting (supportsAggressiveRelease()). If not, the release mode is reset to ConnectionReleaseMode.AFTER_TRANSACTION. This setting is only safe in environments where we can either re-acquire the same underlying JDBC connection each time you make a call into ConnectionProvider.getConnection() or in auto-commit environments where it does not matter if we re-establish the same connection

Thursday, May 10, 2012

Hibernate Logging

We can use two ways of hibernate configuration for debugging the sql queries generated by hibernate framework.

1. Using log4j.properties

# Hibernate logging options (INFO only shows startup messages)
Log4j.logger.org.hiernate=INFO

Log4j.rootLogger=INFO, console

#The below logger statement is equivalent to hibernate.show_sql=true
log4j.logger.org.hibernate.SQL = DEBUG

# Log JDBC bind parameter runtime arguments.
# The below logger prints the values binded to sql query and the response from the query.
log4j.logger.org.hibernate.type = TRACE

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=IPDMS[%d{yyyy-MM-dd HH:mm:ss}] %5p (%F:%L) %m%n

2. Hibernate configuration

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

Thursday, October 6, 2011

org.jasypt.exceptions.EncryptionOperationNotPossibleException

Many of us have come across this exception while using encryption in our functionality.

org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an excep tion. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine


Resolution:


As the exception indicates one need to install the latest JCE Policy Jar Files into your JAVA setup.

1. Download the JCE Policy jar files from the below location:

2. The zip file would contain two jar files (local_policy.jar and US_export_policy.jar). 

3. These jar files need to be placed under the following location:

%JAVA_HOME%\jre\lib\security\

Reference Link:

Monday, October 3, 2011

Mule - Expression Splitter Router

The following example is used to simulate the functionality of the expression-splitter-router in mule.

Java Classes:

Fruit:

package com.expressionsplitterrouter;

public abstract class Fruit {

    private String shape;

    public String getShape() {
        return shape;
    }

    public void setShape(String shape) {
        this.shape = shape;
    }

} 


Apple:

package com.expressionsplitterrouter;

public class Apple extends Fruit {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}


Banana:

package com.expressionsplitterrouter;

public class Banana extends Fruit {

    private String form;

    public String getForm() {
        return form;
    }

    public void setForm(String form) {
        this.form = form;
    }

}


FruitBowl:

package com.expressionsplitterrouter;

import java.util.ArrayList;
import java.util.List;

public class FruitBowl {

    private List<Fruit> fruit;

    public List<Fruit> getFruit() {
        return fruit;
    }

    public void setFruit(List<Fruit> fruit) {
        this.fruit = fruit;
    }
    
    public void addFruit(Fruit fruit){
        if (this.fruit == null) {
            this.fruit = new ArrayList<Fruit>();
        }
        this.fruit.add(fruit);
    }

} 


CreateFruitComponent:

package com.expressionsplitterrouter;

public class CreateFruitComponent {

    public FruitBowl createFruit(String start) {
        
        FruitBowl bowl = new FruitBowl();
        
        Apple apple = new Apple();
        apple.setShape("Round");
        apple.setType("Green");
        
        Banana banana = new Banana();
        banana.setShape("Lengthy");
        banana.setForm("Yellow");
        
        bowl.addFruit(apple);
        bowl.addFruit(banana);
        
        apple = new Apple();
        apple.setShape("Rectangular Square");
        apple.setType("Red");
        
        bowl.addFruit(apple);
        return bowl;
    }
} 


AppleComponent:

package com.expressionsplitterrouter;

public class AppleComponent {

    public void displayApple(Apple apple) {

        System.out.println("Apple Component");
        System.out.println(apple.getShape() + "," + apple.getType());
    }
} 


BananaComponent:

package com.expressionsplitterrouter;

public class BananaComponent {

    public void displayBanana(Banana banana) {

        System.out.println("BananaComponent");
        System.out.println(banana.getShape() + "," + banana.getForm());
    }
} 


Mule-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to continue" />

    <model name="ExpressionSplitterRouterModel">
        <service name="CreateMsgService">
            <inbound>
                <stdio:inbound-endpoint
                    connector-ref="stdioIN" system="IN" />
            </inbound>
            <component
                class="com.expressionsplitterrouter.CreateFruitComponent" />
            <outbound>
                <expression-splitter-router
                    expression="fruit" evaluator="bean">
                    <vm:outbound-endpoint path="banana-channel">
                        <payload-type-filter
                            expectedType="com.expressionsplitterrouter.Banana" />
                    </vm:outbound-endpoint>
                    <vm:outbound-endpoint path="apple-channel">
                        <payload-type-filter
                            expectedType="com.expressionsplitterrouter.Apple" />
                    </vm:outbound-endpoint>
                </expression-splitter-router>
            </outbound>
        </service>
        
        <service name="BananaService">
            <inbound>
                <vm:inbound-endpoint path="banana-channel"/>
            </inbound>
            <component class="com.expressionsplitterrouter.BananaComponent"/>
        </service>
        
        <service name="AppleService">
            <inbound>
                <vm:inbound-endpoint path="apple-channel"/>
            </inbound>
            <component class="com.expressionsplitterrouter.AppleComponent"/>
        </service>
    </model>
</mule> 

Mule - Expression recipient list router

The following example is on the usage of the expression-recipient-list-router. This router can be used to extract the endpoints from the message and route it to the corresponding component.

Java Classes:

CreateXmlMessageComponent:


package com.expressrecipienttransformers;

public class CreateXmlMessageComponent {

    public String createMessage(String msg) {

        StringBuilder sb = new StringBuilder();
        sb.append("<message>");
        sb.append("<recipientList>");
        sb.append("<recipient>vm://display-message-channel</recipient>");
        sb.append("<recipient>vm://compute-message-channel</recipient>");
        sb.append("</recipientList>");
        sb.append("<info>");
        sb.append("Hi there");
        sb.append("</info>");
        sb.append("</message>");
        
        
        return sb.toString();
    }
} 

DisplayMessageComponent:

package com.expressrecipienttransformers;

public class DisplayMessageComponent {

    public void displayMessage(String msg) {
        
        System.out.println("Into displaymessage");
        System.out.println(msg);
    }
} 

ComputeMsgComponent:


package com.expressrecipienttransformers;

public class ComputeMsgComponent {

    public void compute(String msg) {
        
        System.out.println("Into compute component");
        System.out.println(msg.length());
    }
} 

mule-config.xml:



<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to continue" />

    <model name="expression-recipient-list-model">
        <service name="expression-recipient-list-serviec">
            <inbound>
                <stdio:inbound-endpoint
                    connector-ref="stdioIN" system="IN" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.CreateXmlMessageComponent"></component>
            <outbound>
                <expression-recipient-list-router
                    expression="/message/recipientList/recipient"
                    evaluator="xpath" />
            </outbound>
        </service>

        <service name="DisplayService">
            <inbound>
                <vm:inbound-endpoint path="display-message-channel" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.DisplayMessageComponent" />
        </service>

        <service name="ComputeService">
            <inbound>
                <vm:inbound-endpoint path="compute-message-channel" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.ComputeMsgComponent" />
        </service>
    </model>
</mule

Friday, September 30, 2011

Mule Expression Transformers

Java Classes:

GameData: 

A simple POJO object.

package com.expressiontransformers;

public class GameData {

    private String gameName;
    private int year;

    public String getGameName() {
        return gameName;
    }

    public void setGameName(String gameName) {
        this.gameName = gameName;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

}

GameInfo:

Another simple POJO that contains the GameData Object.

package com.expressiontransformers;

public class GamingInfo {

    private int gameId;

    private GameData gameData;

    public int getGameId() {
        return gameId;
    }

    public void setGameId(int gameId) {
        this.gameId = gameId;
    }

    public GameData getGameData() {
        return gameData;
    }

    public void setGameData(GameData gameData) {
        this.gameData = gameData;
    }

}


Here we will be using two component classes. One is used to generate the GameInfo Object and the other is used to print the values.

CreateGamingInfoComponent:

package com.expressiontransformers;

public class CreateGamingInfoComponent {

    public GamingInfo create(String msg) {
        GamingInfo info = new GamingInfo();
        info.setGameId(1);
        
        GameData data = new GameData();
        data.setGameName("Cricket");
        data.setYear(2010);
        
        info.setGameData(data);
        return info;
    }
}


GamingComponent:

package com.expressiontransformers;

public class GamingComponent {

    public void addGame(Integer gameId, GameData data) {
        
        System.out.println(gameId);
        System.out.println(data.getGameName());
        System.out.println(data.getYear());
    }
}

Mule-config.xml:

The mule-config.xml uses the expression-transformer in the inbound-endpoint to convert the input GameInfo object to the required values of the GamingComponent.

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to Continue" />

    <model name="RestaurantServiceE">
        <service name="ExpressionFilterService">
            <inbound>
                <stdio:inbound-endpoint system="IN"
                    connector-ref="stdioIN" />
            </inbound>
            <component
                class="com.expressiontransformers.CreateGamingInfoComponent" />
            <outbound>
                <pass-through-router>
                    <vm:outbound-endpoint path="displayGamingInfo-channel" />
                </pass-through-router>
            </outbound>
        </service>

        <service name="DisplayInfoService">
            <inbound>
                <vm:inbound-endpoint path="displayGamingInfo-channel">
                    <expression-transformer>
                        <return-argument expression="gameId"
                            evaluator="bean" />
                        <return-argument expression="gameData"
                            evaluator="bean" />
                    </expression-transformer>
                </vm:inbound-endpoint>
            </inbound>
            <component class="com.expressiontransformers.GamingComponent" />
        </service>
    </model>
</mule>

Monday, September 26, 2011

Log4j, Mx4j and JMX JConsole Configuration in Mule

Sample Configuration File:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2"
    xmlns:https="http://www.mulesource.org/schema/mule/https/2.2"
    xmlns:saaj="http://www.mulesource.org/schema/mule/saaj/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xmlns:mule-xml="http://www.mulesource.org/schema/mule/xml/2.2"
    xmlns:management="http://www.mulesource.org/schema/mule/management/2.2"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd
          http://www.mulesource.org/schema/mule/https/2.2 http://www.mulesource.org/schema/mule/https/2.2/mule-https.xsd
          http://www.mulesource.org/schema/mule/saaj/2.2 http://www.mulesource.org/schema/mule/saaj/2.2/mule-saaj.xsd
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd
          http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd
          http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!--

        Mule Management Console Configurations START............
        Register the Mx4j Console...............................
        Register the JMX Console................................
        Register Log4j Console..................................
    -->
    <management:jmx-default-config port="1098"
        registerMx4jAdapter="true">
        <management:credentials>
            <spring:entry key="vijay" value="vijay123" />
        </management:credentials>
    </management:jmx-default-config>

    <management:jmx-log4j />

    <!-- 
        Mule Management Console Configurations END.
     -->
</mule> 

Handling SOAP Fault with Http Web Service

The sample XML configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2"
    xmlns:https="http://www.mulesource.org/schema/mule/https/2.2"
    xmlns:saaj="http://www.mulesource.org/schema/mule/saaj/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xmlns:mule-xml="http://www.mulesource.org/schema/mule/xml/2.2"
    xmlns:management="http://www.mulesource.org/schema/mule/management/2.2"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd
          http://www.mulesource.org/schema/mule/https/2.2 http://www.mulesource.org/schema/mule/https/2.2/mule-https.xsd
          http://www.mulesource.org/schema/mule/saaj/2.2 http://www.mulesource.org/schema/mule/saaj/2.2/mule-saaj.xsd
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd
          http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd
          http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!--

        Mule Management Console Configurations START............
        Register the Mx4j Console...............................
        Register the JMX Console................................
        Register Log4j Console..................................
    -->
    <management:jmx-default-config port="1098"
        registerMx4jAdapter="true">
        <management:credentials>
            <spring:entry key="vijay" value="vijay123" />
        </management:credentials>
    </management:jmx-default-config>

    <management:jmx-log4j />

    <!-- 
        Mule Management Console Configurations END.
     -->

    <spring:beans>
        <spring:import resource="transformers.xml" />
    </spring:beans>

    <custom-transformer
        class="com.restaurantsrevice.transformers.DocumentToSOAPFaultTransformer"
        name="faultTransformer">
        <spring:property name="propagateHeaders" value="false" />
    </custom-transformer>

    <model name="RestaurantServiceModel">

        <!-- Default Service Exception Strategy -->
        <default-service-exception-strategy>
            <vm:outbound-endpoint path="exception-channel" />
        </default-service-exception-strategy>

        <service name="RestaurantService">
            <inbound>
                <http:inbound-endpoint
                    address="http://localhost:8080/RestaurantService"
                    synchronous="true">
                    <transformers>

                        <!-- Transform Incoming Soap Message to XML String -->
                        <saaj:soap-message-to-document-transformer />
                        <mule-xml:dom-to-xml-transformer
                            returnClass="java.lang.String" />
                    </transformers>
                </http:inbound-endpoint>
            </inbound>
            <outbound>
                <pass-through-router>
                    <vm:outbound-endpoint path="router-channel"
                        synchronous="true" />
                </pass-through-router>
            </outbound>

            <async-reply>
                <vm:inbound-endpoint path="success-response-channel"
                    synchronous="true" />
                <vm:inbound-endpoint path="exception-response-channel"
                    synchronous="true" />
                <single-async-reply-router />
            </async-reply>
        </service>

        <service name="RouterService">
            <inbound>
                <vm:inbound-endpoint path="router-channel"
                    synchronous="true" />
            </inbound>
            <log-component />
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="request-processing-channel"
                        synchronous="true">
                        <transformer ref="addFoodRequestTransformer" />
                    </vm:outbound-endpoint>
                    <wildcard-filter pattern="*AddFoodRequest*" />
                </filtering-router>
            </outbound>
        </service>

        <service name="RequestProcessingService">
            <inbound>
                <vm:inbound-endpoint path="request-processing-channel"
                    synchronous="true" />
            </inbound>
            <component
                class="org.restaurantservice.RestaurantService"></component>
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="success-response-channel">
                        <transformers>
                            <transformer ref="addFoodResponseTransformer" />

                            <!-- Transform XML to SOAP response -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />
                            <saaj:document-to-soap-message-transformer
                                propagateHeaders="false" />
                        </transformers>
                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.AddFoodResponse" />
                </filtering-router>
            </outbound>
        </service>

        <service name="ExceptionService">
            <inbound>
                <vm:inbound-endpoint path="exception-channel"
                    synchronous="true" />
            </inbound>
            <component
                class="com.services.restaurantservice.components.ExceptionHandler" />
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="exception-response-channel"
                        synchronous="true">

                        <transformers>
                            <transformer
                                ref="FoodAdditionFailedExceptionMap" />
                            <!-- Transform to Document Object -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />

                            <!-- Transform to SOAP Fault -->
                            <transformer ref="faultTransformer" />
                        </transformers>

                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.webservice.FoodAdditionFailed" />
                </filtering-router>
                <filtering-router>
                    <vm:outbound-endpoint path="exception-response-channel"
                        synchronous="true">

                        <transformers>
                            <transformer ref="IncompleteRequestExceptionMap" />
                            <!-- Transform to Document Object -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />

                            <!-- Transform to SOAP Fault -->
                            <transformer ref="faultTransformer" />
                        </transformers>

                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.webservice.IncompleteRequest" />
                </filtering-router>
            </outbound>
        </service>
    </model>
</mule> 
Java Code to transform to Soap Fault:
package com.restaurantsrevice.transformers;

import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.module.saaj.SaajUtils;
import org.mule.module.saaj.i18n.SaajMessages;
import org.mule.transformer.AbstractMessageAwareTransformer;
import org.w3c.dom.Document;

public class DocumentToSOAPFaultTransformer extends
        AbstractMessageAwareTransformer {

    private boolean propagateHeaders = true;
    private String headerURI = "http://www.mulesource.org/schema/mule/saaj/2.2";
    private String headerPrefix = "mule-saaj";

    private SOAPFactory soapFactory;
    private MessageFactory messageFactory;

    public DocumentToSOAPFaultTransformer() throws Exception {
        soapFactory = SOAPFactory.newInstance();
        messageFactory = MessageFactory.newInstance();
    }

    public void setPropagateHeaders(boolean propagateHeaders) {
        this.propagateHeaders = propagateHeaders;
    }

    public void setHeaderURI(String headerURI) {
        this.headerURI = headerURI;
    }

    public void setHeaderPrefix(String headerPrefix) {
        this.headerPrefix = headerPrefix;
    }

    public Object transform(MuleMessage muleMessage, String s)
            throws TransformerException {

        Document document = (Document) muleMessage.getPayload();
        SOAPMessage soapMessage;

        try {
            soapMessage = messageFactory.createMessage();
            SOAPBody body = soapMessage.getSOAPBody();

            addFault(body, document);

            if (propagateHeaders) {
                propagateHeaders(muleMessage, soapMessage);
            }
            soapMessage.saveChanges();
        } catch (SOAPException ex) {
            throw new TransformerException(SaajMessages
                    .failedToBuildSOAPMessage());
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Transformation result: "
                    + SaajUtils.getSOAPMessageAsString(soapMessage));
        }

        return SaajUtils.getSOAPMessageAsBytes(soapMessage);
    }

    void propagateHeaders(MuleMessage muleMessage, SOAPMessage soapMessage)
            throws SOAPException {
        for (Object n : muleMessage.getPropertyNames()) {
            String propertyName = (String) n;
            SOAPHeader header = soapMessage.getSOAPHeader();

            Name name = soapFactory.createName(propertyName, headerPrefix,
                    headerURI);
            SOAPHeaderElement headerElement = header.addHeaderElement(name);
            headerElement.addTextNode(muleMessage.getProperty(propertyName)
                    .toString());
        }
    }

    private void addFault(SOAPBody soapBody, Document document)
            throws SOAPException {

        org.w3c.dom.Element docElement = document.getDocumentElement();
        QName qName = new QName(docElement.getLocalName());

        SOAPFault soapFault = soapBody.addFault(qName, docElement
                .getTextContent());

        Detail detail = soapFault.addDetail();
        detail.addChildElement(soapFactory.createElement(docElement));
    }

}