Monday, October 18, 2010

Classes inside interface

Normally, you can’t put any code inside an interface, but a nested class can be part of an interface. Any class you put inside an interface is automatically public and static. Since the class is static, it doesn’t violate the rules for interfaces—the nested class is only placed inside the namespace of the interface. You can even implement the surrounding interface in the inner class.

TestBed: Use nested class to hold test code


public class TestBed {
public void f() {
System.out.println("f()");
}
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
}

Nested classes

If you don’t need a connection between the inner-class object and the outerclass object, then you can make the inner class static. This is commonly called a nested class. To understand the meaning of static when applied to inner classes, you must remember that the object of an ordinary inner class implicitly keeps a reference to the object of the enclosing class that created it. This is not true, however, when you say an inner class is static. A nested class means:
1. You don’t need an outer-class object in order to create an object of a nested class.
2. You can’t access a non-static outer-class object from an object of a nested class.
Nested classes are different from ordinary inner classes in another way, as well. Fields and methods in ordinary inner classes can only be at the outer level of a class, so ordinary inner classes cannot have static data, static fields, or nested classes.

Anonymous inner class

If you’re defining an anonymous inner class and want to use an object that’s defined outside the anonymous inner class, the compiler requires that the argument reference be final.
Anonymous inner classes are somewhat limited compared to regular inheritance, because they can either extend a class or implement an interface, but not both. And if you do implement an interface, you can only implement one.

Thursday, October 14, 2010

Inner vs Nested class

It’s not possible to create an object of the inner class unless you already have an object of the outer class. This is because the object of the inner class is quietly connected to the object of the outer class that it was made from. However, if you make a nested class (a static inner class), then it doesn’t need a reference to the outer-class object.

The link to outer class

When you create an inner class, an object of that inner class has a link to the enclosing object that made it, and so it can access the members of that enclosing object—without any special qualifications. In addition, inner classes have access rights to all the elements in the enclosing class.

Wednesday, October 13, 2010

Asterisk 1.6 change canreinvite to directmedia in sip.conf

Asterisk sip.conf, peer definition: canreinvite option


This peer option in sip.conf is used to tell the Asterisk server to not issue a reinvite to the client unless really necessary. This is used to interoperate with some (buggy) hardware that crashes if we reinvite, such as the common Cisco ATA 186.

When SIP initiates the call, the INVITE message contains the information on where to send the media streams. Asterisk uses itself as the end-points of media streams when setting up the call. Once the call has been accepted, Asterisk sends another (re)INVITE message to the clients with the information necessary to have the two clients send the media streams directly to each other.

  • If one of the clients is configured with canreinvite=NO, Asterisk will not issue a re-invite at all.
  • If the clients use different codecs, Asterisk will not issue a re-invite.
  • If the Dial() command contains ''t'', ''T", "h", "H", "w", "W" or "L" (with multiple arguments) Asterisk will not issue a re-invite.

'canreinvite=no' stops the sending of the (re)INVITEs once the call is established. From messages in the archives and the Asterisk handbook one finds out that the Cisco ATA-186 does not handle the (re)INVITE well. This is necessary if the client and the Asterisk server is on opposite sides of a NAT gateway or firewall.

  • canreinvite = yes "allow RTP media direct"
  • canreinvite = no "deny re-invites"
  • canreinvite = nonat "allow reinvite when local, deny reinvite when NAT"
  • canreinvite = update "use UPDATE instead of INVITE"
  • canreinvite = update,nonat "use UPDATE when local, deny when NAT"

Note: In spite of its name 'canreinvite' being set to 'no' does *NOT* disable all reINVITE operations. It *only* controls Asterisk generating reINVITEs for the specific purpose of setting up a direct media path. If a reINVITE is needed to switch a media stream to inactive (when placed on hold) or to T.38, it will still be done, regardless of this setting!

Migration from Asterisk 1.2 to 1.4: The "canreinvite" option has changed. canreinvite=yes used to disable re-invites if you had NAT=yes. In 1.4, you need to set canreinvite=nonat to disable re-invites when NAT=yes. This is propably what you want. The settings are now: "yes", "no", "nonat", "update". Please consult sip.conf.sample for detailed information.

Notes

  • reinvite=yes/no is plain wrong, even if you see it mentioned in example .conf files. The correct syntax is canreinvite=yes/no
  • Connecting media paths direct to an endpoint behind NAT won't be pretty. Especially if both devices are behind NAT. You might want to try using SER's nathelper in conjunction since nathelper.so can rewrite the SDP so that the private IP addresses are not included in the re-invite.
  • When dtmfmode=rfc2833, asterisk will send the RTP stream through asterisk. With dtmfmode=info canreinvite works properly.

A longer explanation

[Based on a posting to asterisk-users mailing list]

> I've set canreinvite=no on the channel to the SIP provider and it
> immediately worked. O.k., I'm happy about that but I want to
> *understand* what's going on here.
> .
> My setup is:
>
> Asterisk is connected on one side via eth1 to the "outside world" (IP
> adress 81.223.xxx.xxx) and on the other side via eth0 to the internal
> LAN (eth0 has IP 192.168.1.200, SNOM phone has 192.168.1.201, ...).

A good question, for which it's hard to give a short answer :-)

Firstly, you need to understand how SIP itself was designed to set up calls between handsets.

The SIP 'INVITE' message says "I want to set up a call". In the body of this message is a block of SDP (Session Description Protocol) which says "my audio endpoint is IP x.x.x.x port x, and I can use codecs A, B and C".

In the intended architecture of SIP, the INVITE is forwarded via a series of proxies until it reaches the requested destination. The remote end responds with a 200 saying "OK, my audio stream is on IP y.y.y.y port y, and I choose codec B", which is sent back to the first phone. At this point, the first phone starts sending RTP audio packets from x.x.x.x:x to y.y.y.y:y, and the second phone sends them from y.y.y.y:y to x.x.x.x:x. That is, the audio path is direct, whereas the SIP messages went via intervening proxies.

[This is horrendously over-simplified, but it's enough to make the point]

Now, the second thing to understand is that Asterisk is not a SIP proxy, and its default behaviour is to set up the two legs as two separate audio streams: phone X to Asterisk and Asterisk to phone Y. The way this works is:

  • Phone sends INVITE saying "I am on IP x.x.x.x:x, I can use codecs A,B,C"

  • Asterisk decides where the next leg is. If it is another SIP device, it sends a fresh SIP INVITE (with a different Call-Id) to the second phone saying "I am on IP z.z.z.z:z1, I can use codecs C and D" where z.z.z.z is Asterisk's own IP address and :z1 is a port it has chosen.

  • This arrives at the second phone, which says "OK, I am on IP y.y.y.y:y, I choose codec C", and sends it back to Asterisk

  • Asterisk is happy, so it completes the first leg by replying to the first phone "OK, I am on IP z.z.z.z:z2, I choose codec C"

So now the first phone is sending packets between x.x.x.x:x and z.z.z.z:z2, and the second phone is sending packets between y.y.y.y:y and z.z.z.z:z1

This means that Asterisk is in the media path - each RTP packet has to be received and resent, in both directions. On the minus side, this means more workload on the Asterisk server. On the plus side, being in the media stream means that Asterisk can perform a whole bunch of useful voice services - recording, conferencing, call parking, music on hold, even codec conversion (i.e. the stream from phone X to Asterisk can be using one codec, and phone Y to Asterisk a different one)

With me so far?

The third thing to realise is that Asterisk can optimise this out so that the media path is set up directly between the endpoints. This is what it means by "native bridging" - connecting two compatible endpoints directly together, instead of relaying the audio via Asterisk.

So, under the right conditions, the SIP message Asterisk sends to the second phone will contain the IP address of the first phone, and vice versa. This means it looks and smells almost like a SIP proxy.


Note: Asterisk is still really not a SIP proxy in this case. The two legs have different Call-Ids, and so are different SIP calls. However the SDP descriptors for the audio of the two calls point directly at each other.

This short-circuit way of setting up calls was introduced in 1.4; for earlier versions, I believe the call is set up initially as two legs, and then Asterisk reconnects the endpoints directly using a re-INVITE
--> try directrtpsetup=yes


What do I mean by "the right conditions"? Well I'm not sure what the complete set is, but one of those conditions is that both SIP channels must be marked "canreinvite=yes". If either has "canreinvite=no", then Asterisk falls back to the default behaviour of setting up two separate legs.

In your case, you need the default behaviour when calling the provider, because the SIP phone is on a private IP 192.168.1.201, whilst the provider is on a public IP P.P.P.P. If the SIP messages were to try to set up a direct media path between the two it wouldn't work [*]; in particular, there's no point the public SIP provider trying to send an RTP packet to 192.168.1.201, because it won't be able to route to it.

[*] To be fair, if you have a NAT firewall between your internal network and the Internet, then some packets will be able to go directly between your network and the outside world, with the firewall modifying the source IP address and/or port in the process. There are a whole bunch of nasty tricks which can be done, both on the phone and at the provider, which mean that if you are really lucky you can make VoIP work this way. However I recommend you avoid this. You are in the fortunate situation that your Asterisk box has a real public IP address, so make use of it.


The last thing, which took me a while to figure out, is why the option which means "I prefer to use a direct RTP media path" is called "canreinvite=yes".

Even if the normal audio path for a call can be set up with native bridging, Asterisk sometimes needs to be able to re-insert itself into the media path in the middle of a call - to provide services such as music on hold, transfer, parking and so on when they are requested.

The SIP mechanism for this is called re-INVITE. Two phones which are happily talking to each other can have the media stream changed mid-call using this mechanism, so Asterisk can unstitch the direct link and re-connect the two legs to itself.

However, not all phones support this mechanism. If you set canreinvite=no on a SIP channel, it's saying "this phone doesn't support the re-INVITE mechanism for reconnecting the audio mid-call". Asterisk therefore decides that it must insert itself into the media stream for the whole duration of the call, so that it is already there if later on one of the parties requests one of these in-call features.

Hopefully that's enough to answer your question :-) The best way to see what's going on is to look at the SIP/SDP packets themselves, which you can do either using 'sip debug' in Asterisk, or using tcpdump:

   # tcpdump -i eth0 -n -s0 -v udp port 5060
   # tcpdump -i eth1 -n -s0 -v udp port 5060

With a recent version of tcpdump, the -v option will show you the SIP/SDP payload. If it doesn't, use -X instead (capital X) which will show you hex and ASCII. -s0 means capture the whole packet, and -n means don't try to do reverse DNS lookups on every packet's IP address.

Monday, October 11, 2010

Interfaces and factories

An interface is intended to be a gateway to multiple implementations, and a typical way to produce objects that fit the interface is the Factory Method design pattern. Instead of calling a constructor directly, you call a creation method on a factory object which produces an implementation of the interface—this way, in theory, your code is completely isolated from the implementation of the interface, thus making it possible to transparently swap one implementation for another.

Saturday, October 9, 2010

Multiple inheritance

In a derived class, you aren’t forced to have a base class that is either abstract or "concrete" (one with no abstract methods). If you do inherit from a non-interface, you can inherit from only one. All the rest of the base elements must be interfaces. You place all the interface names after the implements keyword and separate them with commas. You can have as many interfaces as you want. You can upcast to each interface, because each interface is an independent type.

When you combine a concrete class with interfaces this way, the concrete class must come first, then the interfaces. (The compiler gives an error otherwise.)

Keep in mind that one of the core reasons for interfaces is to upcast to more than one base type (and the flexibility that this provides). However, a second reason for using interfaces is the same as using an abstract base class: to prevent the client programmer from making an object of this class and to establish that it is only an interface.

This brings up a question: Should you use an interface or an abstract class? If it’s possible to create your base class without any method definitions or member variables, you should always prefer interfaces to abstract classes. In fact, if you know something is going to be a base class, you can consider making it an interface

Strategy design patern

Creating a method that behaves differently depending on the argument object that you pass it is called the Strategy design pattern. The method contains the fixed part of the algorithm to be performed, and the Strategy contains the part that varies. The Strategy is the object that you pass in, and it contains code to be executed.

Covariant return types

Java SE5 adds covariant return types, which means that an overridden method in a derived class can return a type derived from the type returned by the base-class method.

Friday, October 8, 2010

Interfaces method is public

To create an interface, use the interface keyword instead of the class keyword. As with a class, you can add the public keyword before the interface keyword (but only if that interface is defined in a file of the same name). If you leave off the public keyword, you get package access, so the interface is only usable within the same package. An interface can also contain fields, but these are implicitly static and final.
You can choose to explicitly declare the methods in an interface as public, but they are public even if you don’t say it. So when you implement an interface, the methods from the interface must be defined as public. Otherwise, they would default to package access, and you’d be reducing the accessibility of a method during inheritance, which is not allowed by the Java compiler.

Monday, October 4, 2010

Dynamic binding

All method binding in Java uses late binding unless the method is static or final (private methods are implicitly final). This means that ordinarily you don’t need to make any decisions about whether late binding will occur — it happens automatically.

Why would you declare a method final? It prevents anyone from overriding that method. Perhaps more important, it effectively "turns off" dynamic binding, or rather it tells the compiler that dynamic binding isn’t necessary. This allows the compiler to generate slightly more efficient code for final method calls. However, in most cases it won’t make any overall performance difference in your program, so it’s best to only use final as a design decision, and not as an attempt to improve performance.

Sunday, October 3, 2010

Overriding final method

"Overriding" can only occur if something is part of the base-class interface. That is, you must be able to upcast an object to its base type and call the same method. If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class, and it just happens to have that name, but if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method; you’ve just created a new method. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined.

final keyword

With a primitive, final makes the value a constant, but with an object reference, final makes the reference a constant. Once the reference is initialized to an object, it can never be changed to point to another object. However, the object itself can be modified; Java does not provide a way to make any arbitrary object a constant. (You can, however, write your class so that objects have the effect of being constant.) This restriction includes arrays, which are also objects.

A field that is both static and final has only one piece of storage that cannot be changed. (that is, compile-time constants)

Composition vs. inheritance

In object-oriented programming, the most likely way that you’ll create and use code is by simply packaging data and methods together into a class, and using objects of that class. You’ll also use existing classes to build new classes with composition. Less frequently, you’ll use inheritance. So although inheritance gets a lot of emphasis while learning OOP, it doesn’t mean that you should use it everywhere you possibly can. On the contrary, you should use it sparingly, only when it’s clear that inheritance is useful. One of the clearest ways to determine whether you should use composition or inheritance is to ask whether you’ll ever need to upcast from your new class to the base class. If you must upcast, then inheritance is necessary, but if you don’t need to upcast, then you should look closely at whether you need inheritance.