Read system property using proxy service deployed in WSO2 ESB

Here i have added sample synapse configuration to get carbon server home property and return it as response. Add this configuration and invoke proxy service. You will get carbon.home as response.




<proxy name="EchoProxyTest"
          transports="https http"
          startOnLoad="true"
          trace="disable">
      <description/>
      <target>
         <inSequence>
            <sequence key="responseTest1"/>
         </inSequence>
         <outSequence>
            <send/>
         </outSequence>
      </target>
   </proxy>
 <sequence name="responseTest1">
      <script language="js">var carbonHome = java.lang.System.getProperty("carbon.home");
      mc.setPayloadXML(&lt;serverHome&gt;{carbonHome}&lt;/serverHome&gt;);</script>
      <header name="To" action="remove"/>
      <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
      <property name="RESPONSE" value="true"/>
      <send/>
      <log level="full"/>
   </sequence>

How to write sample class mediator to get system property and inject to synapse properties / How to generate response with synapse property using script mediator

Here i have added class mediator code and sample synapse configuration to get carbon server home property. To test this create java project and add following class mediator code file to /repository/components/lib directory and add following synapse configuration to source view.  Then you can invoke created proxy service.

Class mediator code.

package main.java.org.wso2.carbon.custommediator;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
public class SampleCustomMediator extends AbstractMediator {

public boolean mediate(MessageContext synapseMsgContext) {
    String carbonHome = System.getProperty("carbon.home");
    log.info("Carbon Home is : "+carbonHome);
    synapseMsgContext.setProperty("CARBON_HOME", carbonHome);
    return true;
 }
 


Synapse configuration.

 
<proxy name="EchoProxyTest"
          transports="https http"
          startOnLoad="true"
          trace="disable">
  <target>
   <inSequence>
     <class name="main.java.org.wso2.carbon.custommediator.SampleCustomMediator"/>
     <sequence key="responseTest"/>
   </inSequence>
   <outSequence>
      <send/>
   </outSequence>
 </target>
</proxy>
<sequence name="responseTest">
      <script language="js">var carbonHome = mc.getProperty("CARBON_HOME");
      var carbonHomeTest = "sanjeewa";
      mc.setPayloadXML(&lt;serverHome&gt;{carbonHome}&lt;/serverHome&gt;);</script>
      <header name="To" action="remove"/>
      <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
      <property name="RESPONSE" value="true"/>
      <send/>
      <log level="full"/>
</sequence>



You can invoke create proxy service by calling following URL
https://130.76.202.98:9443/services/EchoProxyTest

Then you will get following response.
 
<serverHome>/home/sanjeewa/work/packs/wso2esb-4.8.0</serverHome>

WSO2 API Manager - Basic user operations curl command( How to do basic operations using curl commands)

Here in this post i will list out curl commands that required to cover complete API Manager (basic) use case. Here we will do fallowing operations. Here we need to login API Manager publisher and store multiple times. Here user will be tenant user(ttt@ttt.ttt). if need change any parameter.

1) Create APIs
2) Publish APIs
3) Create application
4) Subscribe to APIs for that application
5) Remove subscriptions
6) Remove application
7) Remove APIs

API Publisher
=============
curl -X POST -c cookies http://localhost:9763/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=ttt@ttt.ttt&password=tttttt'

1) Create APIs
curl -X POST -b cookies http://localhost:9763/publisher/site/blocks/item-add/ajax/add.jag -d "action=addAPI&name=sanjeewa-api&context=/sanjeewa-api&version=1.0.0&tier=Bronze&tier=Gold&transports=http&http_checked=http&transports=https&https_checked=https&description=sanjeewa-api&visibility=public API&tags=sanjeewa-api,api&resourceCount=0&resourceMethod-0=GET,PUT,POST,DELETE,OPTIONS&resourceMethodAuthType-0=Application & Application User,Application & Application User,Application & Application User,Application & Application User,None&uriTemplate-0=/*&resourceMethodThrottlingTier-0=Unlimited, Unlimited, Unlimited, Unlimited, Unlimited&tiersCollection=Bronze,Gold,Silver,Unlimited" -d 'endpoint_config={"production_endpoints":{"url":"http://search.twitter.com","config":null},"endpoint_type":"http"}'

2) Publish APIs
curl -X POST -b cookies 'http://localhost:9763/publisher/site/blocks/life-cycles/ajax/life-cycles.jag' -d 'action=updateStatus&name=sanjeewa-api&version=1.0.0&provider=ttt@ttt.ttt&status=PUBLISHED&publishToGateway=true&requireResubscription=true'

API Store
=========
curl -X POST -c cookies http://localhost:9763/store/site/blocks/user/login/ajax/login.jag -d 'action=login&username=ttt@ttt.ttt&password=tttttt'

3) Create application
curl -X POST -b cookies http://localhost:9763/store/site/blocks/application/application-add/ajax/application-add.jag -d 'action=addApplication&application=sanjeewa-application&tier=unlimited&description=&callbackUrl='

4) Subscribe to APIs for that application
curl -b cookies http://localhost:9763/store/site/blocks/application/application-list/ajax/application-list.jag?action=getApplications
Got app id for sanjeewa-application each time and used it for further calls.

curl -X POST -b cookies http://localhost:9763/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag -d 'action=addSubscription&name=sanjeewa-api&version=1.0.0&provider=ttt@ttt.ttt&tier=Unlimited&applicationId=7'

5) Remove subscriptions
curl -X POST -b cookies http://localhost:9763/store/site/blocks/subscription/subscription-remove/ajax/subscription-remove.jag -d 'action=removeSubscription&name=sanjeewa-api&version=1.0.0&provider=ttt@ttt.ttt&applicationId=7'

6) Remove application
curl -X POST -b cookies http://localhost:9763/store/site/blocks/application/application-remove/ajax/application-remove.jag -d "action=removeApplication&application=sanjeewa-application"

API Publisher
=============
curl -X POST -c cookies http://localhost:9763/publisher/site/blocks/user/login/ajax/login.jag -d 'action=login&username=ttt@ttt.ttt&password=tttttt'
7) Remove APIs
curl -X POST -b cookies http://localhost:9763/publisher/site/blocks/item-add/ajax/remove.jag -d "action=removeAPI&name=sanjeewa-api&version=1.0.0&provider=ttt@ttt.ttt"

How to avoid web application deployment faliures due to deployment listener class loading issue. - WSO2 Application Server

WSO2 Application server can be use to deploy web applications and services. For some advance use cases we might need to handle deployment tasks and post deployment tasks. There can be listeners defined globally in repository/conf/tomcat/web.xml to achieve this as follows.

<listener>
  <listener-class>com.test.task.handler.DeployEventGenerator</listener-class>
</listener>



When we deploy web application to WSO2 Application Server sometimes class loading environment can be changed. To fix this we can deploy the webapp with "Carbon" class loading environment. For some use cases we are shipping CXF/Spring dependencies within the web application so any class loader environment other than "CXF" might fail. 

To fix this we need to add file named webapp-classloading.xml to META-INF. Then content should be as follows.

<Classloading xmlns="http://wso2.org/projects/as/classloading">
   <Environments>Carbon</Environments>
</Classloading>

How to avoid dipatching Admin service calls to ELB services - WSO2 ELB

We can front WSO2 services by WSO2 ELB. If we have this kind of deployment all requests to services should route through WSO2 ELB. Some scenarios we might need to invoke admin services deployed in servers through ELB. If you send request to some of back end servers admin service load balancer will try to find that service it self. To avoid that we need to define different service path. So admin services in ELB can access through defined service path and other services will not mix up with it.

For this Then we can change ELB's service context to /elbservices/. Edit  servicePath property in axis2.xml as follows.

<parameter name="servicePath">elbservices</parameter>

How to retrive property and process/iterate them in synapse using xpath and script mediator - WSO2 ESB

Sometimes we need to retrieve properties and manipulate them according to custom requirement. For this i can suggest you two approaches.



01. Retrieve roles list and fetch them using script mediator.
//Store Roles into message context
 <property name="ComingRoles" expression="get-property('transport','ROLES')"/>

//Or you can you following if property is already set to default message context
 <property name="ComingRoles" expression="get-property(''ROLES')"/>


//process them inside script mediator
<script language="js">
            var rolelist = mc.getProperty('ComingRoles');
//Process rolelist and set roles or required data to message context as follows. Here we set same role set
            mc.setProperty('processedRoles',rolelist);
</script>
 <log>
            <property name="Processed Roles List" expression="get-property('processedRoles')"/>
</log>





02. Retrieve roles list and fetch them using xpath support provided.
//Retrive incoming role list
  <property name="ComingRoles" expression="get-property('transport','ROLES')"/>

//Or you can you following if property is already set to default message context
 <property name="ComingRoles" expression="get-property(''ROLES')"/>

//Fetch roles one by one using xpath operations
         <property name="Role1"
                   expression="fn:substring-before(get-property('ComingRoles'),',')"/>
         <property name="RemainingRoles"
                   expression="fn:substring-after(get-property('transport','ROLES'),',')"/>

//Fetch roles one by one using xpath operations
         <property name="Role2"
                   expression="fn:substring-before(get-property('RemainingRoles'),',')"/>
         <property name="RemainingRoles"
                   expression="fn:substring-after(get-property('RemainingRoles'),',')"/>

//Fetch roles one by one using xpath operations
         <property name="Role3" expression="(get-property('RemainingRoles'))"/>

//Then log all properties using log mediator
         <log>
            <property name="testing" expression="get-property('Role1')"/>
         </log>
         <log>
            <property name="testing" expression="get-property('Role2')"/>
         </log>
         <log>
            <property name="testing" expression="get-property('Role3')"/>
         </log>

//Check whether roles list having String "sanjeewa". If so we will set isRolesListHavingSanjeewa as true else its false.
         <log>
            <property name="isRolesListHavingSanjeewa"
                      expression="fn:contains(get-property('transport','ROLES'),'sanjeewa')"/>
         </log>


You will find xpath expressions and sample here(http://www.w3schools.com/xpath/xpath_functions.asp)

Trust all hosts when send https request – How to avoid SSL error when we connect https service

Sometimes when we write client applications we might need to communicate with services exposed over SSL. Some scenarios we might need to skip certificate check from client side. This is bit risky but if we know server and we can trust it we can skip certificate check. Also we can skip host name verification. So basically we are going to trust all certs. See following sample code.

//Connect to Https service     
HttpsURLConnection  conHttps = (HttpsURLConnection) new URL(urlVal).openConnection();
                conHttps.setRequestMethod("HEAD");
                //We will skip host name verification as this is just testing endpoint. This verification skip
                //will be limited only for this connection
                conHttps.setHostnameVerifier(DO_NOT_VERIFY);
                //call trust all hosts method then we will trust all certs
                trustAllHosts();
                if (conHttps.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    return "success";

               }
//Required utility methods
static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection
                .setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...