Mule accessing cookies example

0

In this article we will look into Mule’s support of reading and writing cookies. In order to write a cookie, set cookie as an outbound property to the message being sent.

Map<String, Object> props = new HashMap<String, Object>();
props.put("Cookie", String.format("%s=%s", "blogName", "JavArticles"));
MuleMessage message = new DefaultMuleMessage("", props, ctx);

Or simply configure them on the endpoint. For example, below we set the cookie during the response stage.

<http:response-builder>            
    <http:set-cookie name="#['topic']" value="#['cookie-read-write']"/>
</http:response-builder>

We have an http server running at localhost:8888.

<http:inbound-endpoint address="http://localhost:${port}" exchange-pattern="request-response"/>

There is a REST service at path “/cookieAccess”.

        <jersey:resources>
            <component>
                <spring-object bean="cookieAccessComponent"/>
            </component>
        </jersey:resources>

We access the cookie sent as a parameter value.

public Response accessCookie(@Context HttpHeaders hh,
            @CookieParam(value = "blogName") String blogNameCookie) {
        ...
        System.out.println("blogName=" +  blogNameCookie);
        ... 
    }

In the end, we add a new cookie “blogVerified: true” to the http response.

Response.ok("Cookie access OK").cookie(new NewCookie("blogVerified", "true")).build(); 

CookieAccessComponent:

package com.javarticles.mule;

import java.util.Map;

import javax.ws.rs.CookieParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

@Path("/cookieTest")
public class CookieAccessComponent {
    @POST
    @Produces("text/plain")
    public Response accessCookie(@Context HttpHeaders hh,
            @CookieParam(value = "blogName") String blogNameCookie) {
        Map<String, Cookie> cookies = hh.getCookies();
        System.out.println("cookies size" +  cookies.size());
        System.out.println("blogName=" +  blogNameCookie);
        return Response.ok("Cookie access OK").cookie(new NewCookie("blogVerified", "true")).build();       
    }
    
}

Here is the complete mule context.

muleContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:http="http://www.mulesoft.org/schema/mule/http"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans"
      xmlns:jersey="http://www.mulesoft.org/schema/mule/jersey"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
    	http://www.mulesoft.org/schema/mule/jersey http://www.mulesoft.org/schema/mule/jersey/current/mule-jersey.xsd

    	http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">

    <http:connector name="httpConnector" enableCookies="true"/>

    <spring:bean id="cookieAccessComponent" class="com.javarticles.mule.CookieAccessComponent"/>

    <flow name="RequestEchoService">
        <http:inbound-endpoint address="http://localhost:${port}" exchange-pattern="request-response"/>
        <jersey:resources>
            <component>
                <spring-object bean="cookieAccessComponent"/>
            </component>
        </jersey:resources>
       <http:response-builder>            
            <http:set-cookie name="#['topic']" value="#['cookie-read-write']"/>
        </http:response-builder>
    </flow>

</mule>

Let’s invoke the flow now.
We create a cookie and send to the inbound http endpoint as a property. Mule automatically sets it to the http call. The same cookie we access it in the REST service as the parameter value.

Map<String, Object> props = new HashMap<String, Object>();
props.put("Cookie", String.format("%s=%s", "blogName", "JavArticles"));
MuleMessage message = new DefaultMuleMessage("", props, ctx);
...
MuleMessage result = ctx.getClient().send("http://localhost:8888/cookieTest", message, httpRequestOptions);
System.out.println(result.getInboundProperty("set-cookie"));

Finally we print the cookie set in the flow and in the REST service.

MuleCookieAccessExample:

package com.javarticles.mule;

import java.util.HashMap;
import java.util.Map;

import org.mule.DefaultMuleMessage;
import org.mule.api.MuleContext;
import org.mule.api.MuleMessage;
import org.mule.api.context.MuleContextBuilder;
import org.mule.api.context.MuleContextFactory;
import org.mule.config.DefaultMuleConfiguration;
import org.mule.config.spring.SpringXmlConfigurationBuilder;
import org.mule.context.DefaultMuleContextBuilder;
import org.mule.context.DefaultMuleContextFactory;
import org.mule.module.http.api.client.HttpRequestOptions;
import org.mule.module.http.api.client.HttpRequestOptionsBuilder;

public class MuleCookieAccessExample {
    public static void main(String[] args) throws Exception {
        System.setProperty("port", "8888");
        DefaultMuleConfiguration dmc = new DefaultMuleConfiguration();
        dmc.setId("muleexample");
        dmc.setWorkingDirectory("/esb/mule");
        SpringXmlConfigurationBuilder configBuilder = new SpringXmlConfigurationBuilder(
                "muleContext.xml");
        MuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();
        contextBuilder.setMuleConfiguration(dmc);
        MuleContextFactory contextFactory = new DefaultMuleContextFactory();
        MuleContext ctx = contextFactory.createMuleContext(configBuilder,
                contextBuilder);
        ctx.start();
        try {
            Map<String, Object> props = new HashMap<String, Object>();
            props.put("Cookie", String.format("%s=%s", "blogName", "JavArticles"));
            MuleMessage message = new DefaultMuleMessage("", props, ctx);
            final HttpRequestOptions httpRequestOptions = HttpRequestOptionsBuilder.newOptions().method("POST").build();
            MuleMessage result = ctx.getClient().send(
                    "http://localhost:8888/cookieTest", message, httpRequestOptions);
            System.out.println(result.getInboundProperty("set-cookie"));
        } finally {
            ctx.dispose();
        }
    }
}

Output:

cookies size1
blogName=JavArticles
cookiename=null
[blogVerified=true;Version=1, topic=cookie-read-write]

Download the source code

This was an example about reading and writing cookies.

You can download the source code here: muleAccessingCookiesExample.zip
Share.

Comments are closed.