Tuesday, May 1, 2012

How to check whether a server started successfully?

Do you know the IP address and port of your server? Then you can use the following code to detect  whether the server has started up. Also if it's not already started the ServerStartupDetector thread will examine the server socket for period of 'TIME_OUT'.

/**
 * This thread tries to detect a server startup, at a given InetAddress and a port
 * combination, within some time period.
 */
public class ServerStartupDetector extends Thread {
    
    /**
     * Time this tries to recover AgentService (in milliseconds).
     */
    private static final long TIME_OUT = 60000;
    
    private InetAddress serverAddress;
    private int port;
    
    public ServerStartupDetector(InetAddress address, int port) {
        serverAddress = address;
        this.port = port;
    }
    
    public void run() {
        
        boolean isServerStarted;
        
        long startTime = System.currentTimeMillis();

        // loop if and only if time out hasn't reached
        while ((System.currentTimeMillis() - startTime) < TIME_OUT) {
            
            try {
                isServerStarted = isServerStarted(serverAddress, port);
                
                System.out.println("Server has started in address: "+serverAddress.getHostAddress()
                                   +" and port: "+port);
                
                if (isServerStarted) {
                    // do something you want
                    break;
                }

                // sleep for 5s before next check
                Thread.sleep(5000);
                
            } catch (Exception ignored){
                //do nothing
            }
        }
        
    }
    
    /**
     * Checks whether the given ip, port combination is not available.
     * @param ip {@link InetAddress} to be examined.
     * @param port port to be examined.
     * @return true if the ip, port combination is not available to be used and false
     * otherwise.
     */
    private static boolean isServerStarted(InetAddress ip, int port) {

        ServerSocket ss = null;

        try {
            ss = new ServerSocket(port, 0, ip);
            ss.setReuseAddress(true);
            return false;

        } catch (IOException e) {
        } finally {

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return true;

    }

}

You can invoke the above thread as follows.
String ip = "192.168.1.2";
String port = "9443";
        
InetAddress address = InetAddress.getByName(ip);
        
ServerStartupDetector detector = new ServerStartupDetector(
                                       address, Integer.parseInt(port));
        
detector.run();


Monday, April 30, 2012

Writing Apache Synapse Mediators Programmatically....

Hi All,

I'm back with another post, I know this is after some time. Anyway by this post I'm going to address a whole new thing i.e. writing a Apache Synapse mediator programmatically, without adding in any configuration file. This is useful when you need more control over the initialization of your custom mediators.

First of all if you do not know how to write a Synapse mediator, please refer to following two excellent posts.


Now in order to generate a Synapse mediator programmatically, you still need to have your custom mediator class (say XMediator) which extends org.apache.synapse.mediators.AbstractMediator as in [1]. 

I want my mediator to be a child mediator of InMediator, which in turn is a child mediator of Main SequenceMediator. And it's always better to add your mediator as the first child of InMediator, if you want it to be used every time. 

Before doing that we need to have SynapseEnvironment with us (to access the main sequence). Following code segment grabs the SynapseEnvironment from org.apache.axis2.context.ConfigurationContext.

Here's the code segment which does are original requirement. Please ignore those red marked errors, I had to change the names etc.


After adding your mediator to SynapseEnvironment, Synapse take cares of invoking mediate(MessageContext synCtx) method of it.

Hope someone find this useful! 




Friday, March 2, 2012

Documentation on WSO2 ESB's Connection Debug Object's logs

This is a documentation I created upon a Client's request. Should thank Hiranya for helping me out on this.

A connection debug object would be accumulated during request processing, but make use only if the connection encounters issues during processing.

Abbreviations

C2E: Client to ESB
E2C: ESB to Client
E2S: ESB to back-end Server
S2E: back-end Server to ESB


Log
Meaning
C2E-Req-ConnCreateTime
Time that the client created a connection with ESB.
C2E-Req-StartTime
Time that the ESB started processing the client request.
C2E-Req-EndTime
Time that the ESB finished processing the client request.
C2E-Req-URL
This is the request URI obtained from the request line of a request from client to ESB. The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. [1]
C2E-Req-Protocol
This is the protocol version obtained from the request line of a request from client to ESB.
C2E-Req-Method
This is the method token obtained from the request line of a request from client to ESB. (eg: GET, POST etc. [1])
C2E-Req-IP
Remote Client IP address where the request came from.
C2E-Req-Info
HTTP header of the request from client to ESB.
E2C-Resp-Start
Upon the request from client, ESB sends out a response back to the client. This is the time that the ESB started to send the response.
E2C-Resp-End
This is the time that the ESB completed sending the response.
E2S-Req-Start
Start time of the last request sent from ESB to a back-end server.
E2S-Req-End
Completion time of the request sent from ESB to a back-end server.
E2S-Req-ConnCreateTime
Time that the ESB created a connection with a back-end server.
E2S-Req-URL
URI of the back-end service (EndpointReference) that the last request is headed to.
E2S-Req-Protocol
This is the protocol version obtained from the request line of the last request from ESB to back-end server.
E2S-Req-Method
This is the method token obtained from the request line of the last request from ESB to back-end server. (eg: GET, POST etc. )
E2S-Previous-Attempts
This provides details on the previous request sent by ESB to the back-end server.
S2E-Resp-Start
Time that the ESB receives a response from a back-end server.
S2E-Resp-End
Time that the ESB complete processing a response from a back-end server.
S2E-Resp-Status
This is the status line of the response received by the ESB. The first line of a Response message is the Status-Line, consisting of the protocol version followed by a numeric status code and its associated textual phrase, with each element separated by SP characters.
S2E-Resp-Info
HTTP header of the response from the back-end server to ESB.
Total-Time
(E2C-Resp-End) - (C2E-Req-StartTime)
Svc-Time
(S2E-Resp-End) - (E2S-Req-Start)
ESB-Time
(Total-Time) - (Svc-Time)

  • You can find conversion patterns of logs etc. in “log4j.properties” file located at “{$ESB_HOME}/lib” folder.
  • You can find log files inside “{$ESB_HOME}/repository/logs” folder.
  • You can see HTTP headers and messages if you add “log4j.logger.org.apache.synapse.transport.nhttp.wire=DEBUG” line into your “log4j.properties” file.
  • You can set the log level of org.apache.synapse to DEBUG, to enable debugging for mediation.
  • Please see [2] for various log4j conversion patterns.

References


Wednesday, February 29, 2012

Filtering Related Re-directions of WSO2 Stratos

I've created a HTML5 presentation recently on filtering related re-directions of WSO2 Stratos. If you are interested you can see it here. (Chromium web browser is preferred.)

All these filters are JSP filters, which capture a certain URL pattern and direct it to another URL. You can learn more about JSP filters from here.

Sunday, January 29, 2012

Desktop Capturing Software for Ubuntu

I had a terrible time finding a good desktop capturing software for Ubuntu, so thought to write a post since I don't want you to get into the same trouble. I first tried "RecordMyDesktop", it is all good other than the format it outputs! As far as I could see, it only output in ".ogv" format. But I wanted to have it in AVI/mpeg format. Then I tried to find a converter. Downloaded some converters, but converted videos were in really bad quality.

This made me to search bit more. Then I found "XVidCap" software, which saved my day! It worked really well, and I recommend you to use it! You can easily search for it in Ubuntu Software Center and install!

Monday, September 19, 2011

A new design to Frame2Relex Component of OpenCog

Input

Set of frames.

Onetime steps (should be done beforehand and serialize)
Step 1

Extract all unique frame templates from mapping rules (RelEx2Frame) file.

Eg: ^1_Arriving:Manner($Arriving,$var0)

Step 2 – Frame-Rule Bitmap

Create a bitmap for each frame template (of step 1 list) whose length is the number of rules (RelEx2Frame), where each bit corresponds to a unique rule i.e. if the ith frame template is present in the jth rule, the jth bit of the ith bitmap is set to 1.

Step 3 – Rule-Frame Bitmap

Create a bitmap for each rule (RelEx2Frame) whose length is the number of frame templates, where each bit corresponds to a unique frame template i.e. if the ith frame template is present in the jth rule, the ith bit of the jth bitmap is set to 1.

Step 4

Serialize all bitmaps.

Algorithm

Step 1

De-serialize all bitmaps.

Step 2

For each frame in the input: (eg: ^1_Entity:Entity(John,John) )

    Find the matching frame templates. (i.e. ^1_Entity:Entity($var0,$var0) )
  
Step 3

Perform 'OR' operation on Frame-Rule bitmaps of matching frame templates to obtain the Frame-Rule bitmap which corresponds to the possible rules that the input frames represent. Thus, we obtain a subset of rules using the positions that are true.

Step 4

All the rules obtained from step 3 are not necessarily the rules that are valid, since in some rules there are multiple frames as consequent. Thus, we perform a check on the subset of rules obtained from step 3, using the Rule-Frame bitmaps.

For each rule in the subset of rules:
    We check whether all its consequent frame templates are present in the frame templates correspond to input frames.

From this step we obtain a subset of rules (i.e. all necessary rules) of rules obtained at step 3.

Step 5

For each necessary rule:
    Using corresponding actual frames we map variables (eg: $var0, $Time) of this rule.
    We take its conditional part and remove all the 'NOT' true relations and 'OR' relations (ideally we should not remove 'OR' conditions, but handling this is tough/impossible?). Thus we take only the standalone 'TRUE' relations and 'TRUE' relations joined with an 'AND'. Note these are relation templates (eg: _subj($var0,$var1) ).
    We substitute values of variables in relation templates and obtain the actual relex relations.


That's it! :) Of course this will not provide all the relex relations that are needed to form a sentence, due to the limitations in existing RelEx2Frame rules.

Test case:

Input:

^1_Entity:Entity(John,John)

^1_Being_named:Entity(John)

^1_Transitive_action:Agent(throw,John)

^1_Cause_motion:Agent(throw,John)

^1_Cause_motion:Theme(throw,ball)

^1_Transitive_action:Patient(throw,ball)


Output:


noun(John)

_subj(throw,John)

_obj(throw,ball)

person(John)

Sunday, August 7, 2011

Setting up a Huawei 3G Modem in Ubuntu 10.04

After a loooong time, got a chance to write a post (since it's short).

I was planning to buy a HSDPA dongle for a quite a some time now, but didn't feel it is that necessary since I have an ADSL connection at my home and there's WIFI and LAN connections at University. But a recent incident made me to buy one and I bought a Huawei E171 dongle.

When I try it on my Ubuntu 10.04 it showed nothing but the software (mostly exe files) inside the USB. Then I tried creating a new connection under 'Mobile Broadband' and try to connect, still it failed to connect. :( (totally frustrated)

Then I Googled a bit and found out that I need to install "usb-modeswitch" package, due to a known bug.

So I ran, "sudo apt-get install usb-modeswitch", and I saw that it installs an additional package called "usb-modeswitch-data".

After reconnecting my dongle and connecting to the connection I created under 'mobile broadband', I was able to connect to the Internet successfully!

Just thought to share, in case some of you get into the same trouble in future! :-)

See you all with another post!