Thursday, 8 June 2017

Textual Representation of logo

How to make Poller Component Efficient In MULE ESB

Poller in MULE ESB is a very important component when you want to keep polling a endpoint for changes and then process it . Most of the times we do not know how big the changes will be and how much time will it take to complete . So setting polling interval becomes very crucial , because you do not want to trigger a new process before completing the existing task , and also you do not want to lose too much time waiting for the next trigger , if you complete the process earlier .

Following code snippet solves your problem , it achieves synchronous behavior and poller will wait if the process is taking some time , it also achieves asynchornous efficiency where if you have 10 results then 10 separate process will be executed and main poller flow will still wait for them to complete .


Code is self explanatory , i have used simple request reply and aggregator pattern , hope it helps .
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:batch="http://www.mulesoft.org/schema/mule/batch" xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
 xmlns:spring="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/batch http://www.mulesoft.org/schema/mule/batch/current/mule-batch.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    
    
    
    <flow name="exampleFlow" processingStrategy="synchronous" >
     
         <poll doc:name="Poll" >
          <fixed-frequency-scheduler frequency="10000" timeUnit="MILLISECONDS"></fixed-frequency-scheduler>
          <logger message="Upload tour poll started" level="DEBUG"></logger>
          
         </poll>
        
        <expression-component>
         payload = new java.util.ArrayList();
         payload.add("test");
         payload.add("test2");
        </expression-component>
        <choice >
         <when expression="#[payload.size()  &gt;0]">
          <request-reply doc:name="Request-Reply" >
               <vm:outbound-endpoint exchange-pattern="one-way" path="download_tour_vm" doc:name="VM">
                           <collection-splitter />
               </vm:outbound-endpoint>
               <vm:inbound-endpoint exchange-pattern="one-way" path="aggregated_download_tour_vm" doc:name="VM">
                           <collection-aggregator />
               </vm:inbound-endpoint>
    </request-reply>
           <logger message="COMPLETED EXAMPLE" level="INFO"/> 
         </when>
         <otherwise>
          <logger message="No Record To Process" level="INFO"/>
         </otherwise>
        
        </choice>   
        
    </flow>
    
    
    
    
    
    
    <flow name="downloadTour">
       <vm:inbound-endpoint  path="download_tour_vm" doc:name="VM"/>
       
       <scripting:component doc:name="Groovy">
            <scripting:script engine="Groovy"><![CDATA[sleep(20000);
return message.payload;]]></scripting:script>
        </scripting:component>
    </flow>

    
</mule>

Post comments and suggestions .!!

Friday, 17 February 2017

Textual description of firstImageUrl

How to create AWS - s3 bucket using terraform

                   Digitized and Automated Infrastructure is all we need !!!
 Before we begin learning and coding our infrastructure, let us know why we need it.

Think you have an infrastructure in AWS where you have multiple s3 buckets/instances/ELB/ALB/SG/ VPC/Gateways/NAT attached to these resources and most importantly everything is bought up manually.

?? What happens when some resource goes down (😨 😨) and most of them are dependent, you break your head in this mundane job searching and fixing your resources one at a time and testing everything.

?? What if we come up with an idea to write the infrastructure and enable debugging with fixing at a place where every resource will be up and running. And it is all about spinning and getting out of your infrastructure in less or no time. Here is what Terraform  provides you .


Terraform enables you to safely and predictably create, change, and improve infrastructure.
It is an open source tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned. 



Terraform Features:
  • Infrastructure as Code
  • Execution Plans
  • Resource Graph
  • Change Automation

Running a marathon using terraform ....


Let's not waste our time and start creating an s3 bucket in AWS  using terraform.

Terraform supports almost all of the providers, I choose AWS to create my infra in this blog, You can use yours.

Before proceeding make sure you have an AWS account to create your infrastructure. Follow the steps to create a s3 infra :(Install terraform from Terraform Installation Guide )
mkdir ~/terraform_infra
cd ~/terraform_infra
touch s3.tf
Lets go through the Code Step wise :



Provider.tf

The provider block here says we are using aws as our provider where :

  • region : Region where our resource will be created
  • Key/Secret : Provided by AWS

resource.tf

The resource block says what resource we are creating in infra.
Here aws_s3_bucket is resource which terraform understands to create bucket
echo_stage_bucket is our reference to s3 bucket

  • bucket: bucket name that will be created in aws
  • acl: bucket type (public/private)
  • tags: tags your environment
Bootstrap Thumbnail Third

storage.tf

data block (terraform_remote_stage) is used to say terraform that where we want to store our terraform state file

This is needed because once we create the infrastructure we need to version and maintain state if we loose it , we lost our infrastruture state , Here I am using s3 to store my tf state
  • backend: where to store the state file
  • bucket: bucket name we are referencing the bucket that we have created
  • key : filename that will be saved

Final Script s3.tf :


 ➜ terraform plan

+ aws_s3_bucket.echo_stage_bucket
    acceleration_status: ""
    acl:                 "private"
    arn:                 ""
    bucket:              "echo_stage_test_bucket"
    bucket_domain_name:  ""
    force_destroy:       "false"
    hosted_zone_id:      ""
    region:              ""
    request_payer:       ""
    tags.%:              "2"
    tags.Environment:    "Dev"
    tags.Name:           "EchoStage Bucket"
    versioning.#:        ""
    website_domain:      ""
    website_endpoint:    ""

<= data.terraform_remote_state.store_tf_state
    backend:        "s3"
    config.%:       "4"
    config.bucket:  "echo_stage_test_bucket"
    config.key:     "state_file/terraform.tfstate"
    config.profile: "default"
    config.region:  "us-east-1"


Plan: 1 to add, 0 to change, 0 to destroy.


Lets Create the infra : 


➜ terraform apply
aws_s3_bucket.echo_stage_bucket: Creating...
  acceleration_status: "" => ""
  acl:                 "" => "private"
  arn:                 "" => ""
  bucket:              "" => "echo_stage_test_bucket"
  bucket_domain_name:  "" => ""
  force_destroy:       "" => "false"
  hosted_zone_id:      "" => ""
  region:              "" => ""
  request_payer:       "" => ""
  tags.%:              "" => "2"
  tags.Environment:    "" => "Dev"
  tags.Name:           "" => "EchoStage Bucket"
  versioning.#:        "" => ""
  website_domain:      "" => ""
  website_endpoint:    "" => ""
aws_s3_bucket.echo_stage_bucket: Still creating... (10s elapsed)
aws_s3_bucket.echo_stage_bucket: Creation complete
data.terraform_remote_state.store_tf_state: Refreshing state...

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate

 
You would have got the terraform.tfstate state file in your local , Lets push this to created s3 bucket:

Exceute:
➜  terraform-infra terraform remote  config -backend=s3  -backend-config="bucket=echo_stage_test_bucket" -backend-config="key=state_file/terraform.tfstate" -backend-config="region=us-east-1"

Remote state management enabled

Remote state configured and pulled.


For any Queries Send Mail

Monday, 13 February 2017

Textual Representation of logo

How to use Apache HttpClient 4.5 for Https Connections

This is a simple example on how to use Apache HttpClient 4.5 with connection pool manager to request https urls .
package com.javaroots;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.*;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javaroots.DummyTrustManager;

public class HttpClientFactory {

    private static CloseableHttpClient client;

    private static PoolingHttpClientConnectionManager connPool = null;

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class);

    static{
        try
        {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
            sslcontext.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom());
            sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(final String s, final SSLSession sslSession) {

                            return true;
                        }
                    });

            Registry r = RegistryBuilder. create()
                    .register("https", factory).build();

            connPool = new PoolingHttpClientConnectionManager(r);
            // Increase max total connection to 200
            connPool.setMaxTotal(200);
            
            connPool.setDefaultMaxPerRoute(20);


            client = HttpClients.custom().
                    setConnectionManagerShared(true).
                    setConnectionManager(connPool).
                    setSSLSocketFactory(factory).build();
        }
        catch(Exception e){
            LOGGER.error("Error initiliazing HttpClientFactory :: ",e);
        }
    }

    public static CloseableHttpClient getHttpsClient() throws KeyManagementException, NoSuchAlgorithmException  {

        if (client != null) {
            return client;
        }
        throw new RuntimeException("Client is not initiliazed properly");

    }
    public static void releaseInstance() {
        client = null;
    }
}

In above code if you do not use setConnectionManagerShared(true) , you might get following error .
java.lang.IllegalStateException: Connection pool shut down
Now if you want to use HttpClient to call Https Urls and with help of connection pools , you have to add a registry in your connection pool , otherwise it will ignore your SSLContext configurations , and give following error .
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
 at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
 at sun.security.validator.Validator.validate(Validator.java:260)
 at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
 at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
 ... 80 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
 at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
 at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
 ... 86 more
package com.javaroots;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;



public class ApacheClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApacheClient.class);


 public static void main(String[] args) throws Exception{
  CloseableHttpClient apacheClient = HttpClientFactory.getHttpsClient();


  CloseableHttpResponse response2 = null;
  HttpGet httpPost = new HttpGet("https://mms.nw.ru/");
  RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000)
    .build();
  HttpEntity entity2 = null;
  try {
   httpPost.setConfig(defaultRequestConfig);
   response2 = apacheClient.execute(httpPost);

   System.out.println(response2.getStatusLine());

  } catch (Exception e) {
   LOGGER.error("Error while getting response: ", e);
   throw new HttpClientException(e);
  } finally {
   try {
    response2.close();
    apacheClient.close();
   } catch (Exception e) {

   }

  }
 }



}

Monday, 6 February 2017

Textual Representation of logo

Dockerizing an existing Rails application

  Docker is a relatively new and rapidly growing project that allows creating very light “virtual machines”.

Prerequisites

There are no specific skills needed for this tutorial beyond a basic comfort with the command line and using a text editor. The following services are needed:
  • Docker Hub (Login - Signup if you haven't )
  • A Rails application

Setting up your computer

Getting all the tooling setup on your computer can be a daunting task, but thankfully as Docker has become stable, getting Docker up and running on your favorite OS has become very easy. First, we'll install Docker.
Until a few releases ago, running Docker on OSX and Windows was quite a hassle. Lately, however, Docker has invested significantly into improving the onboarding experience for its users on these OSes, thus running Docker now is a cakewalk. The getting started guide on Docker has detailed instructions for setting up Docker on Mac, Linux, and Windows.
Once you are done installing Docker, test your Docker installation by running the following:
$ docker run hello-world

Hello from Docker.

This message shows that your installation appears to be working correctly.
...
Starting with a Rails Application: I will not be going through docker commands as that would be found on dockers website and many blog sites. There are different ways you can deploy your Ruby applications in a Docker container. You can either choose one of the many existing Ruby images on the public docker registry

Building the base image

This image will set a base for the rest of the post as we will use the resulting image to create our set of Rails images.
The image will contain all the things Rails expects to compile and run properly on a Debian based OS. I am not going to talk about the required packages, instead, I am going to focus on the separation of concerns and configuration of the set of images.
One thing to keep in mind is that the image we’ll build is only for RubyOnRails and will not contain any database related packages. If there’s a need to install a gem with native extensions requiring “extra” packages those should go into that specific image unless all of your apps require it.
What should you expect from this image?
This image will not complain about any TTY warnings during installation because of the flag(noninteractive) we are using, all your applications will use as encoding(en_US.UTF-8) .thencoding.
Find the below Image and explanation as followed.
  • I am using ruby 1.9.3 for my Project.
  • Gemfile is already built with rails 3.2.3, You can use your own Gemfile.
#Dockerfile
FROM ubuntu:trusty  # Using Ubuntu OS
MAINTAINER "Santosh Mohanty <santa.jyp@gmail.com>" # Maintainer Name
RUN apt-get update # Updating OS

ENV PATH /usr/local/rvm/bin:$PATH  # Set ENV Path

RUN apt-get update && apt-get -y upgrade && apt-get -y install ruby 1.9.3 # Installation of Ruby
RUN ln -sf /usr/bin/ruby1.9.3 /etc/alternatives/ruby

# basics
RUN apt-get install -y build-essential
RUN apt-get install -y mysql-client libmysqlclient-dev openssl libreadline6 
                       libreadline6-dev curl zlib1g zlib1g-dev libssl-dev libyaml-dev
                       libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev
                       ncurses-dev automake libtool bison subversion pkg-  config gawk 
                       libgdbm-dev libffi-dev npm

RUN gem install bundler
ADD Gemfile /app/Gemfile
ADD Gemfile.lock /app/Gemfile.lock
WORKDIR /app
RUN bundle install
ADD . /app      # Adds your Project Structure to docker
ENV ENVIRONMENT development
CMD ["rails","s"]

EXPOSE 3000 # Exposing PORT 3000 for Development

Executing the Image:

Follow the Below steps to Build your Docker Image from Dockerfile:
docker build -t rails_image ~/workspace/PATH_TO_DOCKERFILE
docker run -p 3000:3000 rails_image # Mapping container port 3000 to local port 3000
This would run your rails application inside docker container
Few Imp commands:
docker run -it rails_image /bin/bash # this would bring up the bash prompt of docker
docker images # List Images
docker rmi IMAGE_ID -f  # remove Image
docker ps  # for listing running containers.
You may find difficulties in connecting to DB from Container, This can be solved running a DB Image or pointing to Specific IP of DB instead of local IP.

I will be writing a blog on how to connect MySQL DB Image to Rails Image using docker compose.

Wednesday, 4 January 2017

Textual Representation of logo

GC overhead limit exceeded Out Of Memory Error In JDBC

I have encountered this error when i was trying to insert a big list of object in to database , using jdbc . The list size was approximately 100k . One way to resolve this error to increase your memory size . I double checked my code and found that i have not closed the PreparedStatement Object in my DAO class .

java.lang.OutOfMemoryError: GC overhead limit exceeded
 at java.util.Calendar$Builder.build(Calendar.java:1482)
 at sun.util.locale.provider.CalendarProviderImpl.getInstance(CalendarProviderImpl.java:88)
 at java.util.Calendar.createCalendar(Calendar.java:1666)
 at java.util.Calendar.getInstance(Calendar.java:1655)
 at java.text.SimpleDateFormat.initializeCalendar(SimpleDateFormat.java:657)
 at java.text.SimpleDateFormat.(SimpleDateFormat.java:601)
 at com.mysql.jdbc.PreparedStatement.setTimestampInternal(PreparedStatement.java:4321)
 at com.mysql.jdbc.PreparedStatement.setTimestamp(PreparedStatement.java:4274)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.setTimestamp(DelegatingPreparedStatement.java:147)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.setTimestamp(DelegatingPreparedStatement.java:147)
 at ch.koala.dao.ProductDAO.insert(ProductDAO.java:42)
 at ch.koala.services.ProductSyncJob.execute(ProductSyncJob.java:64)
 at ch.koala.services.RestServices.productSyncJobExecute(RestServices.java:4020)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:187)
 at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:71)
 at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:280)
 at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
 at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
 at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
 at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
 at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1341)
 at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1273)
 at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1223)
 at org.mule.module.jersey.JerseyResourcesComponent.doInvoke(JerseyResourcesComponent.java:159)
 at org.mule.component.AbstractComponent.invokeInternal(AbstractComponent.java:122)
 at org.mule.component.AbstractComponent.access$000(AbstractComponent.java:57)
 at org.mule.component.AbstractComponent$1$1.process(AbstractComponent.java:238)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)

So to solve this issue , if you encounter while using JDBC , just call close method on your PreparedStatement object , after you finished your work on that , and you might get rid of this error .


Please Post Comments and Suggestions !!!

Friday, 30 December 2016

Textual Representation of logo

Malformed Expression Error Mule ESB

I have got the following error when i tried to write java 8 stream in my expression component .
Message               : [Error: Malformed expression]
[Near : {... t.stream().map(a->a+"dd").collect(java.util.stream ....}]
                                   ^
[Line: 5, Column: 46] (org.mule.api.expression.InvalidExpressionException). Message payload is of type: NullPayload
Type                  : org.mule.api.MessagingException
Code                  : MULE_ERROR-29999
JavaDoc               : http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html
Payload               : {NullPayload}
********************************************************************************
Exception stack is:
1. [Error: Malformed expression]
[Near : {... t.stream().map(a->a+"dd").collect(java.util.stream ....}]
                                   ^
[Line: 5, Column: 46] (org.mule.api.expression.InvalidExpressionException)
  org.mule.el.mvel.MVELExpressionLanguage:238 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/expression/InvalidExpressionException.html)
2. [Error: Malformed expression]
[Near : {... t.stream().map(a->a+"dd").collect(java.util.stream ....}]
                                   ^
[Line: 5, Column: 46] (org.mule.api.expression.InvalidExpressionException). Message payload is of type: NullPayload (org.mule.api.MessagingException)
  org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:32 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
********************************************************************************
Root Exception stack trace:
org.mule.api.expression.InvalidExpressionException: [Error: Malformed expression]
[Near : {... t.stream().map(a->a+"dd").collect(java.util.stream ....}]
                                   ^
[Line: 5, Column: 46]
 at org.mule.el.mvel.MVELExpressionLanguage.validate(MVELExpressionLanguage.java:238)
 at org.mule.el.mvel.MVELExpressionLanguage.evaluateInternal(MVELExpressionLanguage.java:189)
 at org.mule.el.mvel.MVELExpressionLanguage.evaluate(MVELExpressionLanguage.java:154)
 at org.mule.el.mvel.MVELExpressionLanguage.evaluate(MVELExpressionLanguage.java:133)
 at org.mule.el.ExpressionLanguageComponent.process(ExpressionLanguageComponent.java:51)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.processor.AsyncInterceptingMessageProcessor.process(AsyncInterceptingMessageProcessor.java:102)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.construct.DynamicPipelineMessageProcessor.process(DynamicPipelineMessageProcessor.java:54)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.interceptor.AbstractEnvelopeInterceptor.process(AbstractEnvelopeInterceptor.java:51)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.processor.AbstractFilteringMessageProcessor.process(AbstractFilteringMessageProcessor.java:40)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.construct.AbstractPipeline$1.process(AbstractPipeline.java:109)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
 at org.mule.construct.AbstractPipeline$3.process(AbstractPipeline.java:207)
 at org.mule.module.http.internal.listener.HttpMessageProcessorTemplate.routeEvent(HttpMessageProcessorTemplate.java:72)
 at org.mule.execution.AsyncResponseFlowProcessingPhase$1.process(AsyncResponseFlowProcessingPhase.java:52)
 at org.mule.execution.AsyncResponseFlowProcessingPhase$1.process(AsyncResponseFlowProcessingPhase.java:47)
 at org.mule.execution.ExecuteCallbackInterceptor.execute(ExecuteCallbackInterceptor.java:16)
 at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:30)
 at org.mule.execution.HandleExceptionIntercepto...
********************************************************************************
And here is my mule flow :
<http:listener path="/foreach/test" config-ref="myRequestConfig"
   allowedMethods="GET" doc:name="HTTP"/>
      <expression-component>
            java.util.ArrayList list = new java.util.ArrayList();
            list.add("abc");
            payload = list;
            payload = list.stream().map(a->a+"dd").collect(java.util.stream.Collectors.Collectors.toList());
         </expression-component>
        
        <logger message="paload : #[payload]" level="ERROR"/>
    </flow>

If anybody knows the answer please comment below .

Thursday, 15 December 2016

Textual Representation of logo

Mule Session And Flow Var Example

This is simple example in mule demonstrating use of SessionVar , FlowVar , SubFlow , Vm , ForEach ,Groovy and Expression Component .
<http:listener-config port="8081" host="0.0.0.0"
  name="myRequestConfig" doc:name="HTTP Listener Configuration">
  <http:worker-threading-profile
   maxThreadsActive="15" />
 </http:listener-config>

<flow name="foreachexample">
<http:listener path="/foreach/test" config-ref="myRequestConfig"
   allowedMethods="GET" doc:name="HTTP"/>
     <logger message="RUNNNING poller ra " level="ERROR"/>
      <expression-component>
            java.util.ArrayList list = new java.util.ArrayList();
            list.add("abc");
            payload = list;
         </expression-component>
        <set-session-variable value="true" variableName="changeMe" doc:name="Session Variable" />
        <set-variable value="true" variableName="myFlowVar" doc:name="Flow Variable" />
        <foreach >
         <logger message="fdsf" level="ERROR"/>
         <flow-ref name="subFlowTest" />
         <flow-ref name="flow2" />
         <vm:outbound-endpoint path="/opt"/>
        </foreach>
        <vm:outbound-endpoint path="/opt"/>
        <logger message="changeme : #[sessionVars.changeMe]" level="ERROR"/>
    </flow>
    
 <sub-flow name="subFlowTest">
  <logger message="changeme flow var in sub flow : #[flowVars.myFlowVar]" level="ERROR"/>
  <logger message="changeme session var in sub flow: #[sessionVars.changeMe]" level="ERROR"/>
  <scripting:component doc:name="sleep">
   <scripting:script engine="groovy">
                <scripting:text><![CDATA[
            java.lang.Thread.sleep(5000);]]></scripting:text>
   </scripting:script>

  </scripting:component>
 </sub-flow>
 <flow name="flow2">
  <vm:inbound-endpoint path="/opt"></vm:inbound-endpoint>
  <logger message="changeme session var in flow 2: #[sessionVars.changeMe]" level="ERROR"/>
  <logger message="changeme flow var in flow 2: #[flowVars.myFlowVar]" level="ERROR"/>
 </flow>

FlowVars do not get lost when you call another flow by using flow-ref , but if you call another flow by vm or any other transport , then the flow variable will be lost and you will not be able to find it in the other flow .

SessionVars will be present in each and every flow till the execution of the call .
This example also demonstrates how can we write java code in our mule file using groovy component and expression component . Make sure to import the packages of the class which you intend to use , otherwise use fully qualified class name in your code .