Resizing images in one line in Linux

Re-sizing images in one line

I hope you all have had the problem when you upload high quality pics to FB or some other social network.
You can use following command to resize the images by 50%. You can change the ratios .. just replace the value you desire with “50%”

first , you need to have ImageMagick

Install ImageMagick with following command

sudo apt-get install imagemagick

Then go to the directory that has photos to be resized
Run following command


mkdir resize;for f in *; do echo "converting $f"; convert $f -resize 50% resize/${f}; done

Then you will see the re-sized files in the resize directory.

Hope this will save someone’s time .. Enjoy !!!

 

Validate a URL with Filter Mediator in WSO2 ESB

In day to day development life, you may have come across this requirement lot of times. When you are getting a url as a field in the request, you may need to validate it.
Whether the url is in correct structure or whether it contains any unallowed characters.

This can be achieved using filter mediator in WSO2 ESB.

Matter is figuring out correct regular expression. So the code structure would be as follows.

<filter source="//url" regex="REGEX">
	<then>
		<log level="custom">
			<property name="propStatus" value="url is valid" />
		</log>
	</then>
	<else>
		<log level="custom">
			<property name="propStatus" value="!!!!url is not valid!!!!" />
		</log>
	</else>
</filter>

Refer to following table to figure out regular expressions for each use case.

Regex Sample
http(s)?:\/\/((\w+\.+){1,})+(\w+){1}\w*(\w)*([: \/][0-9]+)* http or https with host name/domain name with optional port http://www.asanka.com:2131
http(s)?:\/\/((\w+\.+){1,})+(\w+){1}\w*(\w)*([: \/][0-9]+)*[\/\w\?=&]* url with query parameters, special characters like other than ?,&,= not allowed https://www.asanka.com:2131/user/info?id=2&role=admin
http(s)?:\/\/((\w+\.+){1,})+(\w+){1}\w*(\w)*([: \/][0-9]+)*[\/\w]* url without query parameters https://www.asanka.com:2131/user/info
http(s)?:\/\/((\w+\.+){1,})+(\w+){1}\w*(\w)*([: \/][0-9]+)*[\/\w\W]* url with query parameters, special characters https://www.asanka.com:2131/user/info?id=2&role=admin

You can play around with this using following api

https://github.com/asanka88/BlogSamples/blob/master/ESB/urlvalidate.xml

Payload:


<data>
<url>https://www.asanka.com/asdasd?a=b</url>
</data>

api url :

http://localhost:8280/url/validate

 

Try changing the regex and url values from the above table.

 

Happy Coding !!!🙂

Check for existence of element/property with Filter Mediator in WSO2 ESB

In day to day development , sometimes you will need to check for the existence of an element or property or some thing. In other words, you will need to check something if it is null. It can be easily done in WSO2 ESB using filter mediator.

Learning by example is the best way ,

Let’s take a simple example. Suppose there is a payload incoming like below

<user>
 <name>asanka</name>
 <role>admin</role>
</user>

Suppose you need to read this field into a property. and suppose <role/> is an optional element. In that case what are you going to do?

The expected behavior is , if role is not coming with the payload, it is considered as the default role “generic_user”.

So the following code segment of filter mediator will do it for you.

<filter xpath="//role">
   <then>
      <log level="custom">
         <property name="propStatus" value="role is available" />
      </log>
      <property name="userRole" expression="//role" />
   </then>
   <else>
      <log level="custom">
         <property name="propStatus" value="!!!!role is not available!!!!" />
      </log>
      <property name="userRole" value="generic_user" />
   </else>
</filter>

“xpath” attribute in filter element provides the xpath expression to be evaluated.
If the xpath expression is evaluated to “true”, synapse code in the “then” block will be executed.
Otherwise code in the else block will be executed.

If the evaluation of the xpath returns something not null. It will be considered as true. If it is null it will be considered as false.

If you want to play with this, create filter.xml with following content and copy it to

$CARBON_HOME/repository/deployment/server/synapse-configs/default/api

https://github.com/asanka88/BlogSamples/blob/master/ESB/nullcheck.xml

and make an HTTP POST to http://localhost:8280/user/rolecheck with following payloads.

<user>
 <name>asanka</name>
 <role>admin</role>
</user>

Check the log file and you will see following output.


[2016-04-11 22:49:38,041] INFO - LogMediator propStatus = role is available
[2016-04-11 22:49:38,042] INFO - LogMediator status = ====Final user Role====, USER_ROLE = admin

<user>
 <name>asanka</name>
</user>

Check the log file and you will see following output.


[2016-04-11 22:49:43,083] INFO - LogMediator propStatus = !!!!role is not available!!!!
[2016-04-11 22:49:43,084] INFO - LogMediator status = ====Final user Role====, USER_ROLE = generic_user


Hope this helps someone🙂 happy coding ….

[WSO2 ESB] Change local name of an element of the payload

There was a requirement to change the local name of an element in the payload using a parameter in the incoming payload. For example

user sends a following payload to the ESB

<people>
   <action>submit</action>
   <person>
      <name>asanka</name>
   </person>
   <person>
      <name>nuwan</name>
   </person>
   <person>
      <name>bandara</name>
   </person>
</people>

Requirement was, value in

  <action>submit</action> 

to be the root element of the response message like below.

<submit>
<status>SUCCESS</status>
</submit>

Guess what !!! .. it is just following piece of code.

<sequence xmlns="http://ws.apache.org/ns/synapse" name="createPayload">
   
     <property name="RESPONSE_ROOT_TAG" expression="//action/text()" type="STRING"/>
         
        <script language="js">
            var rootElementName=mc.getProperty('RESPONSE_ROOT_TAG');
            mc.getEnvelope().getBody().getFirstElement().setLocalName(rootElementName);
        </script>    
</sequence>

hope this can save someone’s time🙂🙂

Wrap Aggregated Messages in a root element in one go !!

Hi.. this problem wasted a lot of time of mine😦 So I am writing this blog , hope this will save someone’s time . I think you already know about the Aggregate Mediator. It is used to aggregate / collect responses resulted from Clone mediator or Iterate Mediator . I am not going to explain the usage of the Aggregate Mediator here. I hope to explain the behind the scene stuffs of the aggregate mediator in a future post. For the time being , lets just continue with this particular problem.

Suppose there are two back ends that sends following responses.

<userInfo>
   <id>1</id>
   <name>Asanka</name>
</userInfo>
<accountInfo>
   <userId>1</userId>
   <accNo>99239930923</accNo>
   <branchNo>221</branchNo>
</accountInfo>

And the expected response at the client is

<Information>
   <userInfo>
      <id>1</id>
      <name>Asanka</name>
   </userInfo>
   <accountInfo>
      <userId>1</userId>
      <accNo>99239930923</accNo>
      <branchNo>221</branchNo>
   </accountInfo>
</Information>

.Lets get started …

First a clone mediator should be used to send the request to multiple back ends. i am not going to specify back ends. But it looks like below.

<clone id="sa">
   <target>
      <endpoint>
         <address uri="URL_BackEnd1" />
      </endpoint>
   </target>
   <target>
      <endpoint>
         <address uri="URL_BackEnd2" />
      </endpoint>
   </target>
</clone>

Now lets have a look at how the outsequence should look like. Here are the things we have to do in  the outsequnce.

1.Create OM type property to accumulate responses in the Aggregate Mediator.

2.Introducing the Aggregate Mediator to collect responses from back ends.

3.Send them back to the client.

<outSequence>
   <property name="info" scope="default">
      <ns:Information xmlns:ns="www.asankatechtalks.com" />
   </property>
   <aggregate id="sa">
      <completeCondition />
      <onComplete expression="$body/*[1]" enclosingElementProperty="info">
         <send />
      </onComplete>
   </aggregate>
</outSequence>

This is to aggregate the responses inside it. This property is specified inside Aggregate mediator as attribute “enclosingElementProperty” of the <onComplete>.

   <aggregate id="sa">

Attribute “id” specifies the particular Clone mediator that is associated with the Aggregate mediator.

<completeCondition />

This represents the condition to Aggregate mediator to stop the aggregation of responses. Here I have not set this. Since clone has 3 targets, complete condition will be the moment it receives 3 responses.

      <onComplete expression="$body/*[1]" enclosingElementProperty="info">
         <send />
      </onComplete>

here the “expression” is the aggregate expression.This specifies which part of the response should be aggregated.In my case I have given it as the first child of the response body of the each response resulted from the clone mediator.

Then comes the main actor of the film🙂. enclosingElementProperty specifies the OM type property we defined at the beginning of the out sequence. So that property is added to the payload body and aggregated messages goes in to the particular tag created in this property.

 

So you will get the response as explained in the blog post.

Forceful JSON Convertor with WSO2 ESB

Hi all, I am writing this blog after a long time. I am trying to address a one use case I could find when  I was working on a customer issue.Use case is as follows.Forceful JSON Convertor

As show in the above figure , There is a client that sends a any type of message to the ESB and then to the Back end. and Then Back end sends a message with type other than JSON. And there is a use case user wants to access the incoming payload from the Back end in the Script Mediator. using

var payload=mc.getPayloadJSON();

This works perfectly when Backend sends messages of type application/json. If Backend sends a message of any type other than application/json ,  above line of code cannot be used to access the JSON payload inside the script mediator.

i wrote the following custom mediator [1]  to convert the payload into JSON and set it as a property in the message context. So it can be accessed in the script mediator and do what ever you want to do with the payload🙂.

Instructions are as follows.

How to Use

  1. Download Jar [2]  and copy it to CARBON_HOME/repository/components/lib.
  2. Change the Builder and Formatter for application/json in CARBON_HOME/repository/conf/axis2/axis2.xml to

WSO2 ESB 4.7.0

org.apache.axis2.json.JSONStreamFormatter

org.apache.axis2.json.JSONStreamBuilder

WSO2 ESB 4.8.1

org.apache.synapse.commons.json.JsonStreamFormatter

org.apache.synapse.commons.json.JsonStreamBuilder

Then in the out sequence use the following synapse config

 
<outSequence>

<class name="org.wso2.carbon.esb.forceful.json.ForcefulJsonConvertor"/>

<script language="js">
 
var json=mc.getProperty("FORCE_BUILT_JSON");

mc.setPayloadJSON(json);
 
</script>

<property name="messageType" value="application/json" scope="axis2" type="STRING"/>

<send/>

</outSequence>
 

This can be used in the in sequence as well only if the incoming message type is other than application/json. Because if the incoming message type is application/json , getPayloadJSON() can be used to get the json payload in the script mediator. Hope this may be a help .

[1] https://github.com/asanka88/ForcefulJsonConvertor.git

[2]https://github.com/asanka88/ForcefulJsonConvertor/blob/master/Artifact_24-11-2014/ForceJsonConvertor-1.0.0.jar   

Change the private/public key pair of default keystore of wso2 products

WSO2 products comes with a default keystore. There may be a requirement to change the default  public/private key pair that comes in the default keystore. There are several steps you should follow.

1. Remove existing default public/private key pair

2.Create a new public/private key pair

3.Export certificate from key store

4. Import it in to client-trust store

5. Change private key related configurations in the carbon.xml

There is limitation in tomcat. So if you are going to add a new private key to the existing wso2carbon.jks , then the key should have the same password as the keystore. hence password of the new key should be “wso2carbon”.

There can’t be two public/private key pairs in the the same keystore (tomcat limitation). There for existing public/private key pair “wso2carbon” needs to be removed from the keystore.

Download Keystore explorer [1].

Then extract kse-501-install.tar.gz and run install.sh using command


./install.sh

(you need to be the root to perform this operation)

then go in to kse5.0 folder and run kse.sh


./kse.sh

Then open wso2carbon.jks keystore using the keystore explorer.

It will prompt for the keystore password, enter “wso2carbon” as the keystore password.

Then you can see the default public/private key pair as below.

Selection_006

Select it and Press Delete.

So now we have removed default private/public key pair from the wso2carbon.jks default key store.

Now let’s create a new public/private key pair.

Run following commands in the <CARBON_HOME>/repository/resources/security

keytool -genkeypair -alias <ALIAS> -keyalg RSA -keysize 2048 -keypass wso2carbon -keystore wso2carbon.jks

Then you will be asked following deatils .

What is your first and last name?
  [Unknown]:  <Enter host name of the machine >
What is the name of your organizational unit?
  [Unknown]: <provide appropiate one>
What is the name of your organization?
  [Unknown]:  <provide appropiate one>
What is the name of your City or Locality?
  [Unknown]: <provide appropiate one>
What is the name of your State or Province?
  [Unknown]:  <provide appropiate one>
What is the two­letter country code for this unit?
  [Unknown]: <provide appropiate one>

*Note- Please keep the password wso2carbon as it is.

Then this needs to be imported to client-truststore.Execute following commands in the same directory.

to export the certificate from keystore

keytool -export -alias <ALIAS> -file <ALIAS>.pem -keystore wso2carbon.jks -storepass wso2carbon

to import it to the client trust store

keytool -importcert -alias <ALIAS> -keystore client-truststore.jks -file <ALIAS>.pem

Then there are few settings to be changed in carbon.xml.

In the carbon.xml under the Security tag , you can find KeyStore tag. enter your new key paire alias between the KeyAlias tags.
[

<KeyStore>
<!-- Keystore file location-->
<Location>${carbon.home}/repository/resources/security/wso2carbon.jks</Location>
<!-- Keystore type (JKS/PKCS12 etc.)-->
<Type>JKS</Type>
<!-- Keystore password-->
<Password>wso2carbon</Password>
<!-- Private Key alias-->
<KeyAlias>YOUR NEW ALLIAS GOES HERE</KeyAlias>
<!-- Private Key password-->
<KeyPassword>wso2carbon</KeyPassword>
</KeyStore>

and then restart the server.Now your default private/public key pair has been changed. hmmm want to get it confirmed?

Check the certificate information using the Browser…🙂

[1] http://sourceforge.net/projects/keystore-explorer/files/KSE%205.0.1/kse-501-install.tar.gz/download