Saturday, February 26, 2011

Mac OS X Terminal Tips


1. Go to beginning of the current line

Ctrl + A

2. Go to the end of the current line

Ctrl + E

3. Copy the current path

$ pwd | pbcopy

4. Clear the screen [same as clear]

Ctrl + L

5. Display all the environment variables

$ env

6. Deleting from current position to the end of the line

Ctrl + K

7. Deleting from current position to the beginning of the line

Ctrl + U

8. Deleting the first word before current position

Ctrl + W

9. Move the cursor a letter back from the current position

Ctrl + B

10. Move the cursor a letter forward from the current position

Ctrl + F

11. Open current location in Finder window

$ open .

12. Open a file with unknown extension with the default editor

$ open -t file.ext

13. Watch a particular file to see who's opening it

sudo opensnoop -f PathToTheFile

14. Text-to-speech

say "HI"

15. Runs the last command again
!!

16. Hold option and click a position in the current line to move your cursor to that position.

17. List all possible commands
Hit and hold ESC

Sunday, February 20, 2011

Enabling secured browsing with Facebook

Did you know there is an option in Facebook to enable secured browsing..?

Go to Account --> Account Settings --> Account Security and enable HTTPS browsing for your account as shown below.



I am bit surprised though why this isn't enabled by default.

There were many incidents reported where the Facebook sessions were hijacked - using Firesheep - a Firefox add-on.

Wednesday, February 16, 2011

11 GPG Commands One Should NEVER Forget

GnuPG is the GNU project's complete and free implementation of the OpenPGP standard as defined by RFC4880 . GnuPG allows to encrypt and sign your data and communication, features a versatile key management system as well as access modules for all kinds of public key directories.

1. Create GPG Keys
$ gpg --gen-key
2. List the available keys in your keyring
$ gpg --list-keys
3. Exporting the public key - by user id
$ gpg --armor --export <uid>

Example :
$ gpg --armor --export prabath@wso2.com
4. Importing a public key of a trusted user to your keyring
$ gpg --import wso2.gpg
5. Encrypting a document - you need to import the public key corresponding to the uid-of-recipient first in to your keyring as per step - 4.
$ gpg --output <output-file>  --encrypt --recipient <uid-of-recipient>  <input-file>

Example :
$ gpg --output test.txt.gpg  --encrypt --recipient prabath@wso2.com  test.txt
6. Decrypting
$ gpg --output <output-file> --decrypt <input-file>

Example :
$ gpg --output text.txt --decrypt test.txt.gpg
7. Signing a document [detached signature]
$ gpg --armor --output <signature> --detach-sig <file-to-sign>
8. Verifying a signature [detached signature] - you need to have the public key of the person who signed it in your keyring - see step-4.
$ gpg --verify <signature> <original-file>
9. Exporting private keys
$ gpg --armor --output <key-file-name> --export-secret-keys <uid>

Example : 
$ gpg --armor --output prabath.asc --export-secret-keys prabath@wso2.com
10. Uploading your public key to a key server.
$ gpg --keyserver certserver.pgp.com --send-key <uid>
11. Download a key from a key server.
$ gpg --keyserver certserver.pgp.com --recv-key <key_id>

Monday, February 14, 2011

WSO2 ESB Property Mediator - Different Scopes

Properties are name value pairs. Properties are a way to convey information across different processing units. For example user may need to set a transport property from the message mediation. Or user may need to remove a property which is set by the transport. This mediator sets or removes properties for a particular message.

Property mediator has no direct impact on the message but rather on the message context flowing through Synapse. The properties set on a message can be later retrieved through the synapse:get-property(prop-name) XPath extension function. If a scope is specified for a property, the property could be set as a transport header property or an (underlying) Axis2 message context property, or as a Axis2 client option. If a scope is not specified, it will default to the Synapse message context scope. Using the property element with action specified as "remove" you can remove any existing message context properties.

The above extracted from the WSO2 ESB documentation...

This blog post focuses on different types of scopes available while setting properties.

1. Default - or the Synapse
Once you set a property under this scope - the value of it will be available through out both the in/out sequences.

To access this property inside the mediate() method of a mediator...
public boolean mediate(org.apache.synapse.MessageContext mc) {
// Available in both in-sequence and out-sequenc
String propValue = (String) mc.getProperty("PropName");
System.out.println("SCOPE_SYNAPSE : " + propValue);
return true;
}
2. Axis2
Once you set a property under this scope - the value of it will be available only through out the the sequence it's been set. If you set the Property mediator to the in-sequence, you cannot access it in the out-sequence.To access this property inside the mediate() method of a mediator...
public boolean mediate(org.apache.synapse.MessageContext mc) {
org.apache.axis2.context.MessageContext axis2MsgContext;
axis2MsgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();

// Available only in the sequence the property is defined.
String propValue = (String) axis2MsgContext.getProperty("PropName");
System.out.println("SCOPE_AXIS2 : " + propValue);
return true;
}
3. Axis2-Client
This is similar to Synapse scope. The difference is - you can access it in following two ways..
public boolean mediate(org.apache.synapse.MessageContext mc) {
org.apache.axis2.context.MessageContext axis2MsgContext;
axis2MsgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();
String propValue = (String) axis2MsgContext.getProperty("PropName");
System.out.println("SCOPE_AXIS2_CLIENT - 1 : " + propValue);

propValue = (String) axis2MsgContext.getOptions().getProperty("PropName");
System.out.println("SCOPE_AXIS2_CLIENT - 2: " + propValue);
return true;
}
4. Transport
Once you set a property under this scope - it will be added to the transport header of the out going message from the ESB.

Invoking A Secured Web Service With soapUI

Thilina has written a very nice guide on the $subject Available here...

Sunday, February 13, 2011

Accessing the HTTP method within a WSO2 ESB Mediator

I couldn't find this in the ESB property documentation - so thought of keeping a note here.

Also - there is a chance that you can confuse the constant "HTTP_METHOD" with org.apache.axis2.transport.http.HTTPConstants.HTTP_METHOD - which internally refers to ""HTTP_METHOD_OBJECT""
public boolean mediate(org.apache.synapse.MessageContext synCtx) {
org.apache.synapse.core.axis2.Axis2MessageContext.Axis2MessageContext axis2Msgcontext = null;
org.apache.axis2.context.MessageContext msgContext  = null;
axis2Msgcontext = (Axis2MessageContext) synCtx;
msgContext = axis2Msgcontext.getAxis2MessageContext();
String httpMethod = (String) msgContext.getProperty("HTTP_METHOD");
}

Saturday, February 12, 2011

RPC with Java

The goal of RPC in general is make distributed programming as easy as possible by creating the illusion that an exchange of data over the network that results in some processing (on another machine than the one the application is running on) is nothing more than a special kind of procedure call — one that has the special attribute of being “remote”.

Stating the obvious, there is a clear separation of roles in this scenario: the application invoking the procedure (the caller) is called the client, the one executing the procedure is the server. (In more advanced applications, a single program may assume both roles during the course of its execution.)



Unsurprisingly, RPC is the foundation of client/server computing. While RPC started out as a way to provide a transparent programming experience for traditional, procedural models, it was quickly followed by technologies that aimed to do the same for object-oriented programming. Examples include DCOM, CORBA, and RMI.

The first popular RPC solution was introduced by Sun (Sun RPC, later called ONC RPC) together with NFS, the Network File System. It featured all the important parts of more modern incarnations: An interface description with an associated stub/skeleton generator, marshaling, even a (albeit very simple) registry (portmap).

The other important RPC standard is DCE RPC, which is also used as the foundation of Microsoft’s DCOM.

The Sun RPC compiler is called rpcgen. As input, it takes a list of remote procedures (interfaces) defined in an interface definition language (IDL).

The output from rpcgen is a set of files that include...

1. Server code: Main function that sets up a socket, registers the port with a name server, listens for and accepts connections, receives messages, unmarshals parameters, calls the user-written server function, marshals the return value, and sends back a network message.

2. Client stub: The code with the interface of the remote function that marshals parameters, sends the message to the server, and unmarshals the return value.

3. Header: Contains definitions of symbols used by client and server as well as function prototypes

4. Data conversion functions: A separate file may be generated if special functions need to be called to convert between local data types and their marshaled forms.

The rpcgen tool generates code in C - from a given IDL.

Netbula JRPC is a complete port of the C version of ONC RPC to the Java(tm) platform - which generates code in JAVA. In this blog post we'll be using Netbula JRPC.

Also Distinct ONC RPC/XDR for Java - is another vendor who provides an ONC RPC toolkit in java.

Let's first have a look at how a sample IDL file looks like.
type definitions

program identifier { 
   version version_id {
       procedure list
    } = value;
} = value;
type definitions block is used to define structs - for example,
struct person {
string name<>;
int age;
};
Then the program block - a given program block can have different versions of the same interface - and program has a program number to identify it uniquely. In the following example, the program number is 1234567.
program msgserv {
    .................
} = 1234567;
Now let's have a look at the version block. As I mentioned before there can be multiple version blocks inside a given program and each version is identified by the version number. In the following example - the version number is - 1.
program msgserv {
    version MSGSERV_V1 {
     .................... 
     }= 1;
} = 1234567;
Next the procedure list. Inside a one version - there can be set of procedures defined. And there also each procedure is identified with a unique number. In the following example sendmsg() is identified by number - 2 and addperson() is identified by number - 3.
program msgserv {
    version MSGSERV_V1 {
                string sendmsg(string)=2; 
                void addperson(person)=3;     
    }= 1;
} = 1234567;
RPC Call Message
Each remote procedure call message contains the following unsigned integer fields to uniquely identify the remote procedure.
- Program number
- Program version number
- Procedure number

RPC Reply Message
The RPC protocol for a reply message varies depending on whether the call message is accepted or rejected by the network server. The reply message to a request contains information to distinguish the following conditions.
- RPC executed the call message successfully.
- The remote implementation of RPC is not protocol version 2. The lowest and highest supported RPC version numbers are returned.
- The remote program is not available on the remote system.
- The remote program does not support the requested version number. The lowest and highest supported remote program version numbers are returned.
- The requested procedure number does not exist. This is usually a caller-side protocol or programming error.

Let's get our hands dirty.. Following is the complete IDL of our example used here - which is in the file msg.x.
struct person {
string name<>;
int age;
};

program msgserv {
    version MSGSERV_V1 {
      string sendmsg(string)=2; 
      void addperson(person)=3; 
     }= 1;
} = 1234567;
Now, you need to download Netbula JRPC from here. You can find the jrpcgen tool inside the bin folder.

Let's use jrpcgen to generate Java code.
$ jrpcgen msg.x
This generates four files.

1. msgserv.java : The RPC program interface definition, including constant definition such as program number.

2. msgserv_cln.java : The client stub class. This class implements the RPC interface defined above. An RPC client program instantiate an instance of this class and call its methods (remote call).

3. msgserv_svcb.java : The RPC service. This class inherits the RPC interface and is abstract, the programmer needs to extend this class and supply the implmentation for the interface.

4. person.java : The corresponding Java file for the struct person.

Compile all four java files - make sure you have orpc.jar in the classpath. You can find orpc.jar inside the lib directory of Netbula distribution you downloaded.
$ javac msgserv.java person.java msgserv_cln.java msgserv_svcb.java -classpath orpc.dev\lib\orpc.jar
Next let's write the actual service and start it. Following is the code for it - msgsvc.java.
import netbula.ORPC.*;

public class msgsvc extends msgserv_svcb {
        
//implement the server function, 
//let's just echo the msg back
public String sendmsg(String msg) {
 System.out.println("got msg from client "+ msg);
 return msg;
}

public void addperson(person psn) {
 System.out.println("got msg from client");
}

//main function runs the server
public static void main(String srgv[]) {

//let's run the server using the run() method in Svc
//For more flexibility, one could use the TCPServer and UDPServer directly

   new Thread(new PortMapper()).start();

   try {  
     new msgsvc().run(); 
   } catch(netbula.ORPC.rpc_err ex){
      System.out.println("error occured");
   }
  
}

}
class PortMapper implements Runnable {

@Override
public void run() {

 try {
   new Pmapsvc().run();
 } catch (rpc_err e1) {
 }
}
}
Now compile and start the server - msgsvc.java.
$ javac msgsvc.java -classpath .;orpc.dev\lib\orpc.jar
$ java msgsvc  -classpath .;orpc.dev\lib\orpc.jar
Next the client... Following is the code for client.
import netbula.ORPC.*;
               
import java.net.*;
 
public class ClientTest {  
    
public ClientTest () {}
                              
static public void main(String args[]) {
               
try {
               
     msgserv_cln cl = new msgserv_cln(args[0], "udp");            
     String msg = "hello world\n";
               
     System.out.println("sending.. ");
               
     for(int i=0; i<5; i++){
           String reply = cl.sendmsg(msg);
           System.out.println("got " + reply +"\n");
     }
}catch (rpc_err e) {
     System.out.println("rpc: " + e.toString());
}
}
}
Here, we constructed the client which connects to the server on host args[0] with UDP protocol, send a message, and print out the reply.
$ javac ClientTest.java -classpath .;orpc.dev\lib\orpc.jar
$ java ClientTest localhost  -classpath .;orpc.dev\lib\orpc.jar
If you get here - means your sample works fine.. :-) Let's get in to the internals.

You may recall - that I mentioned jrpcgen produces four java classes. One of them is the interface, msgserv.java - which is been implemented by both the client and server side stubs.

Let's have a look at this interface.
public interface msgserv{

 public static final int _def_pno = 1234567;
 public static final int _def_vno = 1;

 public static final int _sendmsg_proc = 2;
 public static final int _addperson_proc = 3;
 
 public String sendmsg(String in_arg) throws netbula.ORPC.rpc_err;
 public void addperson(person in_arg) throws netbula.ORPC.rpc_err;
}
Can you notice that this defined four constants. _def_pno is the program number. _def_vno version number of the interface. Other two are the numbers corresponding to each procedure defined in the IDL.

Now let's have a look at the constructor of the client side stub, instantiated by our ClientTest.java above.
/**
Construct an RPC client object connected to a server
on the specified host with the specified protocol

@param host server hostname, or URL of the RPC proxy if http is used
@param proto protocol, can be "tcp", "udp" or "http"
*/
public msgserv_cln(String host, String proto) throws rpc_err {
 super(host, msgserv._def_pno, msgserv._def_vno, proto);
}
See here in this constructor it passes the program number[_def_pno] and the version number[_def_vno] to construct the instance. So - this particular instance is created for a given version of the given program.

Now you got a very valid question. What if we have multiple versions inside the same program. How does this constructor look like. Well.. in case we have multiple versions - then for each version separate client/server stubs as well as an interface will be generated.

Similarly if you look at the sendmessage() method of client side stub, you will find out - the procedure number is used to invoke the method.

The above emphasizes on the value of having program number, version number and procedure numbers in RPC. Still not happy? Then let's have a look at the server side stub.
public XDT proc_call (int proc, XDR inXDR) throws XDRError {
  switch(proc) {
 case 0:  return new XDTvoid();

 case 2:
         String _out_arg2;
  try {
   XDTString _in_arg = new XDTString();
   _in_arg.xdr(inXDR);
   _out_arg2 = this.sendmsg(_in_arg.value);
  } catch (XDRError e) {
   throw e;
  }
  return new XDTString(_out_arg2);

 case 3:
  try {
   person _in_arg = new person();
   _in_arg.xdr(inXDR);
   this.addperson(_in_arg);
  } catch (XDRError e) {
   throw e;
  }
  return new XDTvoid();

  default: return null;
  }
 }
Here, this the method invoked at the server side when a service method been invoked from the client end.

Here you will see - based on the procedure number, procedure been invoked.

References :

[1]: http://www.innoq.com/blog/st/2005/05/18/rpcstyle_web_services.html
[2]: http://netbula.com/javarpc/msgsamp.html
[3]: http://www.javvin.com/protocol/rfc1831.pdf : RPC: Remote Procedure Call Protocol Specification Version 2 (ONC version)
[4]: http://www.javvin.com/protocol/rfc1057.pdf : RPC: Remote Procedure Call Protocol Specification Version 2 (Sun version)

Thursday, February 10, 2011

Adding custom HTTP headers via Axis2 Client

This post explains how to add custom HTTP headers to a web service request initiated from an Axis2 client.

You may also have a look at this blog post by Keith, which explains how to add custom HTTP header to a response message from Axis2 service end.
// Create an instance of org.apache.axis2.client.ServiceClient
ServiceClient client = ...

// Create an instance of org.apache.axis2.client.Options
Options options = new Options();

List list = new ArrayList();

// Create an instance of org.apache.commons.httpclient.Header
Header header = new Header();

// Http header. Name : user, Value : admin
header.setName("user");
header.setValue("admin");
  
list.add(header);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list);

client.setOptions(options);

Saturday, February 5, 2011

Securing RESTful Services


Video recording available here...

[WSO2 ESB] Invoking a Web Service via HTTPS from a Proxy Service

1. Get the public certificate of the Web Service deployed over HTTPS

2. Import the certificate from [1] to [ESB_HOM]/resources/security/client_truststore.jks

:\>keytool import public_cert.crt -alias myservice -keystore client_truststore.jks

The default password is wso2carbon. You can put any name to alias [e.g. myservice] and need to replace public_cert.crt with name of the certificate you have from [1].

3.You may be using an IP address as the web service end point or the CN of the certificate issued for the end point may not match its server url. This could cause a host name verification error.

To overcome that, find the following in [ESB_HOME]/repository/conf/axis2.xml ..

<parameter name="HostnameVerifier">DefaultAndLocalhost</parameter>

uncomment it and change it to the following...

<parameter name="HostnameVerifier">AllowAll</parameter>

4. If the Web Service or it's WSLD - or the both enabled for mutual authentication - you need export the public certificate of WSO2 ESB out and import it to the trust store of the Web Service.

To export out the ESB public certificate you can use the following.

:\>keytool export -file esb_public_cert.crt -alias wso2carbon -keystore wso2carbon.jks

You can find wso2carbon.jks at [ESB_HOM]/resources/security/wso2carbon.jks and it default password is wso2carbon.

That's it..

Java Class Loading

Class loading is widely viewed as one of the darkest arts in Java development. In this session, Jason Greene will provide insight into the how and why of Java SE, Java EE, JBoss Application Server, JBoss Microcontainer, and OSGi class loading. He will offer historical perspective by beginning with JDK internals and progress to the modern, modular class loader models in use today. In addition, Jason will cover common pitfalls and methodologies to avoid them.

The Zen of Class Loading from JBoss Developer on Vimeo.

Thursday, February 3, 2011

[Blogging] 10 Tips to get 1000 Hits per day

1. Pick the most catching subject

2. Make the content short and sweet

- Essay like content doesn't help. Make the content as short as possible.
- One image worths thousand words - use images whenever appropriate.
- Use syntax-highlighters whenever you publish code.
- Use spacing/gaps as necessary - to make the blog posts more readable
- Use proper tags to tag your blog posts.
- Don't make the blog looks crowded with too many widgets/gadgets.

3. Keep the blog updated regularly

- Blog regularly and make sure you answer readers' comments
- Frequent updates helps to improve Google page rank

4. No anonymous blogging

- Always blog with a human name. That will give the readers' the feeling of being real.
- Post your email address or a way to contact you directly, in the blog

5. Publish on DZone

- DZone is a technology publishing company that produces valuable content for software architects and developers worldwide.
- It has a considerable amount of user base, highly focused on technology related topics.
- Do not publish your links on Weekends.
- Tag your DZone link properly
- Share the DZone link [via DZone]
- Make the DZone link description meaningful/attractive and readable.
- Participate in discussions via comments to the link

6. Publish on reddit

- Reddit is a social news website which has wide variety of topics.
- Pick the most appropriate topic for your link.
- Reddit has a huge user base compared to DZone.

7. Tweet

- Tweet about your blog post.
- Use hash-tags appropriately.
- Publish first in DZone and then Tweet the DZone link.
- Use catching words to describe what you have in the blog post - it need to not be the title always.

8. Share in Facebook

- Post a link to your blog post in Facebook
- Publish first in DZone and then share the DZone link

9. Subscribe to blog aggregators

- Subscribe to appropriate blog aggregators
- Don't publish the entire blog post to feeds. Blogger has an option to limit number of words.

10. Use SEO best practices to improve your Google Page Rank

Tuesday, February 1, 2011

WSO2 Application Server 4.0