Showing posts with label WSO2. Show all posts
Showing posts with label WSO2. Show all posts

Thursday, January 7, 2016

How to use Analytics JavaScript (JS) API in a JavaScript Client

In this post I'm going to create a simple JavaScript Client and show you how to use WSO2 Data Analytics Server 3.0.0 JavaScript API within it.

You can download the WSO2 Data Analytics Server 3.0.0 from here.

Extract the downloaded wso2das-3.0.0.zip file and create a folder inside DAS_HOME/repository/deployment/server/webapps/, with the name analytics-client.

Inside the analytics-client, create a folder with the name js. We keep this folder to store the imported JavaScript files in our web app.

Copy the following files from DAS_HOME/repository/deployment/server/jaggeryapps/portal/js/ into the js folder you created earlier.
  • carbon-analytics.js  
  • jquery-1.10.2.js
Now create the index.html file with the following content inside the analytics-client folder.


 

  DAS JS Client
  
  

  

 
 
 

Analytics JS Client



Now, start the server. Go to DAS_HOME/bin and execute the command, ./wso2server.sh

To invoke your web app from the browser, give the following url.

https://localhost:9443/analytics-client/index.html

Since we have used console.log() to display JavaScript values, activate debugging in your browser with F12, and select "Console" in the debugger menu. 

You can try more JavaScript functions exposed in Analytics JS API referring to the Data Analytics Server documentation.

References :

[1] https://docs.wso2.com/display/DAS300/Analytics+JavaScript+%28JS%29+API
[2] http://www.w3schools.com/js/js_debugging.asp


Tuesday, March 17, 2015

How to see the H2 database content in a WSO2 Product

Every WSO2 product comes with an embedded H2 database as the default database configuration. There can be times we need to see the content of this database.

In this post, I'm going to explain how to see this database content through the H2 console.

First you have to configure the following in the <product-home>/repository/conf/carbon.xml file.

        
        8082
        
 
Once the configuration done as above, start the server(wso2 product you want).

Then open a browser and goto "http://localhost:8082/". You can see the login page as follows.



You need to give the JDBC URL, username and password.

You can find the relevant JDBC URL in the <product-home>/repository/conf/datasources/master-datasources.xml

For example, in ML, it is given as follows;

    WSO2ML_DB
    The datasource used for Machine Learner database
    
        jdbc/WSO2ML_DB
    
    
        
            jdbc:h2:repository/database/WSO2ML_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000
            wso2carbon
            wso2carbon
            org.h2.Driver
            50
            60000
            true
            SELECT 1
            30000
        
    

Copy the url given in the element. Here it is jdbc:h2:repository/database/WSO2ML_DB.

Give the username and password given in the and elements in the above configuration. (The default username and password comes with every wso2 product is admin, admin)

You will see the H2 console like this.



Note :

When you need to do some change in the database of a wso2 product and setup the server with that change, you have to run the startup script as follows.

./wso2server.sh -Dsetup

Note that, in order to apply the changes first you have to delete the contents in the directory <product-home>/repository/database. Then start the server with -Dsetup option.

Friday, January 9, 2015

How to Implement a Class Mediator for WSO2 ESB

A Mediator is simply a processing unit in the ESB. A mediator can do any modification to the messages.

In WSO2 ESB there are so many built-in mediators available. Also we can write custom mediators and add more to the available capabilities of the ESB.

Among those built in mediators Class Mediator is capable of creating an instance of a custom-specified class and set it as a mediator. There are two approaches to create custom mediators.
  • Extend the org.apache.synapse.mediators.AbstractMediator class
  • Implement the org.apache.synapse.api.Mediator interface 

In this post I'm going to show you how to implement a simple Class Mediator and using it in a proxy service.
  1. Create a maven project with the name OrderServiceMediator.
  2. You need to add the following dependency to your pom.xml
  3.         
                org.apache.synapse
                synapse-core
                2.1.2-wso2v4
            
    
  4. Also you will have to configure the required maven repository as follows. If this is not configured once you try mvn clean install it will give the following error.
    [ERROR] Failed to execute goal on project OrderServiceMediator: Could not resolve dependencies for project
  5.         
                wso2-nexus
                WSO2 internal Repository
                http://maven.wso2.org/nexus/content/groups/wso2-public/
                
                    true
                    daily
                    ignore
                
            
    
  6. Here is my pom.xml after configuring everything.
  7. 
        4.0.0
    
        org.wso2.training.manorama
        OrderServiceMediator
        1.0
    
        
        
        
            
                wso2-nexus
                WSO2 internal Repository
                http://maven.wso2.org/nexus/content/groups/wso2-public/
                
                    true
                    daily
                    ignore
                
            
        
    
        
            
                org.apache.synapse
                synapse-core
                2.1.2-wso2v4
            
    
        
        
    
    
Next step is to write the Class Mediator Java code. 
  1. Create a new package called mediator (or any other package name you prefer).  If you skip this step once you try to deploy the mediator in ESB Carbon will not make a bundle from it. So you will get the following error.
    wso2 esb org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
  2. Add a new Java class CustomMediator which extends the AbstractMediator.
  3. Now you will have override the public boolean mediate(MessageContext messageContext) method.
  4. Implement the logic inside this method to do whatever modifications you need to do to the messages .
  5. Here in my simple class mediator I am going to give a discount for the orders submit to the OrderProcessingService which is deployed in the Axis2 server. (This is the same OrderProcessingService described in my previous post).
  6. package mediator;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.synapse.MessageContext;
    import org.apache.synapse.mediators.AbstractMediator;
    
    import javax.xml.namespace.QName;
    
    /**
     * Created with IntelliJ IDEA.
     * User: manorama
     * Date: 1/05/15
     * Time: 10:25 AM
     * To change this template use File | Settings | File Templates.
     */
    public class CustomMediator extends AbstractMediator {
    
        private static final Log log = LogFactory.getLog(CustomMediator.class);
    
        private String discountFactor = "10";
        private String bonusFor = "10";
        private int bonusCount = 0;
    
        @Override
        public boolean mediate(MessageContext messageContext) {
    
            // xs:schema targetNamespace given in the WSDL is "http://ws.apache.org/axis2"
    
            String price = messageContext.getEnvelope().getBody().getFirstElement().
                    getFirstChildWithName(new QName("http://ws.apache.org/axis2","amount")).getText();
    
            int discount = Integer.parseInt(discountFactor);
            int bonusNo = Integer.parseInt(bonusFor);
            double currentPrice = Double.parseDouble(price);
    
            // Discounting factor is deducted from current price form every response
            Double lastPrice = new Double(currentPrice - currentPrice * discount / 100);
    
            // Special discount of 5% offers for the first responses as set in the bonusFor property
            if (bonusCount <= bonusNo) {
                lastPrice = new Double(lastPrice.doubleValue() - lastPrice.doubleValue() * 0.05);
                bonusCount++;
            }
    
            String discountedPrice = lastPrice.toString();
    
            messageContext.getEnvelope().getBody().getFirstElement().
                    getFirstChildWithName(new QName("http://ws.apache.org/axis2","amount")).setText(discountedPrice);
    
            log.info("Order price discounted");
            log.info("Original price: " + price);
            log.info("Discounted price: " + discountedPrice);
    
            return true;
        }
    
        public String getType() {
            return null;
        }
    
        public void setTraceState(int traceState) {
            traceState = 0;
        }
    
        public int getTraceState() {
            return 0;
        }
    
        public void setDiscountFactor(String discount) {
            discountFactor = discount;
        }
    
        public String getDiscountFactor() {
            return discountFactor;
        }
    
        public void setBonusFor(String bonus) {
            bonusFor = bonus;
        }
    
        public String getBonusFor() {
            return bonusFor;
        }
    }
    
    
  7. Note that the setter methods are implemented, to set the required property values through the mediator.
  8. Next we will create the proxy service to the back-end service deployed in the Axis2 server. You can follow the steps mentioned in the WSO2 ESB user guide to create the proxy service. Here is my proxy service configuration.
    
        
            
                
                    
                    
                
            
            
                
                
            
            
                
    scenario1
  9. Now try to send a message to this proxy service and see the discounted price is assigned for to the amount. You can see the resulted value after going through the mediator using this url.

    http://localhost:8080/axis2/services/OrderProcessingService/getAmount?orderID=25

References :
[1] https://docs.wso2.com/display/ESB481/Sample+380:+Writing+your+own+Custom+Mediation+in+Java
[2] https://docs.wso2.com/display/ESB481/Class+Mediator
[3] http://stackoverflow.com/questions/24260091/wso2-esb-jar-file-with-callback-handler-not-loading 

Friday, December 19, 2014

Secure Web Services with WSO2 ESB as Integration Layer

WSO2 ESB supports securing unsecured web services. In this post I'm going to explain how you can secure a web service with WSO2 ESB, using it as an integration layer. 

You may have heard of proxy services. A proxy service is a virtual service hosted within an ESB. Simply a proxy service wraps a back-end web service hosted in an application server.  A proxy service receives messages that have been sent to a specific endpoint (back-end service) defined in the proxy service configuration. Before forwarding the messages to the relevant endpoint the proxy service can process them if needed, using mediators.

These back-end services may no be secured always. In such a case those unsecured services can be made secured by using the ESB as integration layer. To do that what we need to do is creating a secure proxy service with WS-Security enabled with a specified security policy. 

Here are the simple steps to follow to secure a web service.
  1. Open the ESB Management Console.
  2. Create a Proxy Service by clicking on the Services -> Add -> Proxy Service ->Pass Through Proxy in the Main tab. (Here I've selected Pass Through Proxy since I just need to forward messages to the endpoint without performing any processing on them)
  3.  Give a name for the Proxy Service and specify the target endpoint. Here I've given the web service URL which is hosted within the Axis2 server.


  4.  Then you will be redirected to the List of Services.
  5.  You will see the proxy service is shown as 'Unsecured'. Click on 'Unsecured'.


  6. You will be prompted to Enable Security. Select Yes. Then select the UsernameToken as the Basic Scenario.
  7. Click Next. Select user group and Finish.
  8. Now the proxy service is security enabled. You can see the endpoint starting with https:// service dashboard of the proxy service.

Now let's see how to access this web service using a secure client.

References :