Thursday, December 29, 2011
UDP, TCP, RTP, RTSP, Unicast, Multicast...
It sounds a bit complex, all this network protocol stuff! Well, sorry, it can be intimidating. But I promise this will not be too painful if you read slowly. Actually you may find this interesting.
The best I can do is to try to make the concepts simple. Let's start with an assumption that you already know how VBrick does multicasting. For a review of multicasting, see White Papers.
MPEG-1 and MPEG-2 both combine audio and video into a series of 1's and 0's. Exactly how those 1's and 0's are created is defined by the MPEG standards. So, when we say "MPEG-2 Transport Stream", we can look at a document and agree on what we mean. MPEG-1 and MPEG-2 are self sufficient, but they do little to specify exactly how they might be transmitted over IP.
MPEG-4 is also self-sufficient, but rather than defining unique "MPEG" ways of sending video, it specifies sending the video using existing standards. Among those standards are IP, RTP and RTSP, but I'm getting ahead of myself. We must start with simple concepts.
Networking Concepts
TCP
It seems everyone's heard of "TCP/IP". You probably know that "IP" stands for "Internet Protocol". The "TCP" stands for "Transmission Control Protocol". Here is the deal: to ensure a packet arrives without errors, the sender of a packet keeps an extra copy and waits for the receiver to say "I got it okay". If the sender hears this from the receiver, the sender can discard that extra copy. If the receiver says "I didn't get it" or says nothing at all after awhile, the sender resends it. As you can see, this makes for reliable delivery but takes time. It also adds a great deal of overhead because there is a dialog between the sender and receiver. Practically all email, web pages, and other Internet traffic is sent using TCP/IP.
TCP is a key reason why your web traffic or email "slows down" but does not "break". When there is too much traffic, your packets may be discarded or lost somewhere...but not to worry! Without you even knowing it, your packets are being resent until they finally get through (and you thought you just had a "good" connection).
Analogy: TCP is like a telephone call. If you didn't hear what the other person said, you say "What?"
UDP
UDP stands for "User Datagram Protocol". It is sometimes called "send and pray" because there is no dialog between the sender and receiver. If the receiver does not get a packet, the sender will never know. "When the heck would I want that!" you may ask. Well, UDP is very efficient when there is little chance of errors (like in your LAN), or when TCP would provide "too late" delivery.
All VBrick video is sent via UDP. Hey, we are sending live video, right? If I send you video frame #1, #2, #3 .... #1000 and you display the video frames in real time as you receive them, and you didn't get frame #500, what would you do with new frame #500 if I resent it to you? Display it after frame #1000? That wouldn't look too good, would it?
Video is normally send via UDP. But there is trouble with UDP now-adays. Many corporate firewalls block all UDP packets, making it impossible for streaming video to reach desktops. This is done to prevent hackers from getting access to the network, and is also sometimes done to prevent excessive use of bandwidth. More on this later.
Analogy: UDP is like a public address system. If you didn't hear what was announced, you can't hear it again.
RTP
RTP stands for Real-time Transport Protocol. It is normally sent via UDP. It does not ensure "real time" but is a protocol that enhances the control and synchronization of real time stuff (like streaming video). Here is where it gets interesting: with MPEG-1 and MPEG-2, RTP is unnecessary because MPEG itself provides synchronization (see White Paper). Like so many standards, there are several ways to implement it. For example, you can split apart the MPEG-1 stream and send audio on one IP address and video on another, or you can send both audio & video on the same address. RTP provides timestamps that will provide audio/video sync. VBrick has long supported RTP in the VB3000 for interoperability with other vendors.
In the case of MPEG-4, the only meaningful way to send audio/video is via RTP (there is nothing like a "MPEG-1 System Stream" nor a "MPEG-2 Transport Stream"). In other words, for MPEG-4, a/v sync is provided via RTP.
Analogy: RTP is like an orchestra leader, keeping all the musicians in sync.
RTSP
RTSP stands for Real Time Streaming Protocol. RTSP is control protocol, not to be confused with IP, TCP, or UDP. However, RTP and RTSP are linked. You could find RTP without RTSP, but you would not find RTSP without RTP.
A good way to position RTSP in your mind is to think of it the same way you think of "http" and "ftp". You know, if you want to see a web page, you will enter "http://something". If you want to view a video in a player, you will enter "rtsp://something". This is only true for unicast streams, where each viewer receives their own stream from the server (i.e. from the VBrick). RTSP is not used for multicast.
Analogy: RTSP is like a "touch tone" telephone vs. the old rotary dial telephone. It is merely a method of signaling.
HTTP
The Hyper Text Transfer Protocol is often confused with the Hyper Text Markup Language. Its description is beyond the scope of this page, and on the surface seems out of place here. However, because virtually all firewalls allow the default http port (port 80) to pass, streaming video can be sent via http "tunneling". There is a severe penalty, since http is sent via TCP which increases the overhead by some 30% and magnifies the delay.
Unicast
Unicasting is simply sending packets from one source to one destination. For example, from one web server to one (or each) person viewing a page on a web browser. What may be new to you is the idea that one VBrick can send video via unicast to many viewers. More on this in a moment. Data (or video) can be sent via UDP or TCP, with RTP and RTSP, and can be sent via Unicast. So, Unicast is a method, not a protocol.
Analogy: Mailing a letter (although we assume IP is faster!)
Multicast
Multicasting is sending data from a sender to multiple receivers where each receiver signals that they want to receive the data. This is different from Unicasting, and different from broadcasting (where everyone gets the data whether they want it or not). Notice that you normally have a one-way connection, thereby ruling out TCP. Yes, that's right, Multicast is done via UDP. There are methods in use where a receiver can signal a sender that it has received a bad packet using a different 'reverse channel'. This is called "reliable multicast" and has little value for live video transmission.
Analogy: Distributing brochures with a sign that says "Take One". Only those who want it take it.
SDP
The Session Description Protocol, for our purposes, is a file that describes a MPEG-4 stream. SDP files are uniquely created for each stream, whether the stream is multicast or unicast. SDP files are put on servers to allow them to identify a stream and replicate it to viewers. Wow, really new concept! But not to worry, VBrick makes it largely invisible. But you should know the standard exists and we support the relevant sections.
Putting It All Together
Here we go. You can send MPEG-4 video by wrapping the video steam in a RTP packet, wrapping the audio stream in another RTP packet, then wrapping each RTP packet in a UDP packet, then controlling the stream using RTSP. You can encapsulate the RTP in http if necessary (via an external server).
You can send MPEG-1 System and MPEG-2 Transport streams via raw UDP (this is what we normally do in LANs). You can send MPEG-1 System Streams and MPEG-2 transport streams via RTP over UDP (we do this for stored video on demand).
Monday, December 27, 2010
Packet and frame difference
A frame is the PDU of layer 2 (data link) of the OSI model.
At layer 2, packets get encapsulated into frames so that they can be transferred over different media to the end destination. Still the same data...it could be split up differently due to varying window size, but there are a few different details added into the frame header.
a packet is a formatted block of data carried by a packet mode computer network. Computer communications links that do not support packets, such as traditional point-to-point telecommunications links, simply transmit data as a series of bytes, characters, or bits alone. When data is formatted into packets, the bitrate of the communication medium can better be shared among users than if the network would have been circuit switched. By using packet switched networking it is also harder to guarantee a lowest possible bitrate.
In computer networking, a frame is a data packet of fixed or variable length which has been encoded by a data link layer communications protocol for digital transmission over a node-to-node link. Each frame consists of a header frame synchronization and perhaps bit synchronization, payload (useful information, or a packet at higher protocol layer) and trailer. Examples are Ethernet frames and Point-to-point protocol (PPP) frames.
A packet is a group of bits of data. A frame is a place to put a packet.
You can't store a frame -- it is mainly of interest to low level network
hardware. A frame is typically an interval of time. Sometimes, it is the
equivalent region along the length of a wire.
If you look at a very early use of the term "frame" this is clear. In the
RS-232 asynchronous serial line protocol, a packet (though not called
that) is typically 8 bits that represent a byte of data being sent from
one node to another. But on the wire, you have to add a start bit in
front and a stop bit in back. Adding those bits is called "framing." You
will never see the 10 bit sequence stored anywhere - the bits are added on
the fly by hardware. The start and stop bits are not part of any packet.
The time between when the receiver sees the start bit and when the
receiver sees to stop bit, not the 10 bits, is a frame.
In T1, a frame is defined by points in time alone -- no extra bits
involved at all. It's not uncommon on T1 voice lines for the packets to
end up distributed incorrectly among the frames (instead of one packet to
each frame), thus causing individual voice circuits to get messed up.
Wednesday, November 17, 2010
Overview of MPEG-4 encoding format
• MPEG-4 is a standard used to compress audio and visual data. The MPEG-4 standard is generally used for streaming media and CD distribution, video conversation, and broadcast television. MPEG-4 incorporates many features of MPEG-1, MPEG-2 and other related standards.
• MPEG-4 is still a developing standard and is divided into several parts. The standard includes the concept of “profiles” and “levels,” allowing a specific set of capabilities to be defined in a manner appropriate for a subset of applications.
• MPEG-4 is able to crunch massive video files into pieces small enough to send over mobile networks. While these blurry pictures are unlikely to persuade millions of people to upgrade immediately their mobile phones but holds enough promise for future.
• Perhaps more important are the interactive features that MPEG-4 offers. The video functions almost like a Web page, but allowing people to interact with the picture on the screen or to manipulate individual elements in real time.
• MPEG-4 also allows other types of content to be bundled into a file, such as video or images. These files require special software to play.
• MPEG-4 would allow the interactivity of the video which may open potential to do far more than just point and click at links on the screen. Individual elements of the video like a character, a ball in a sporting event, a rocket ship in a science-fiction epic can exist in a separate layer from the rest of the video. This could allow viewers to interact with these elements somehow, even changing the direction of the story.
Overview of H.264 Coding Format:
• Also known as MPEG-4 Part 10 or AVC (for Advanced Video Coding).
• Poised to become the next standard for format of convergence in the digital video industry regardless of the video playback platform . Big Internet players like Google/YouTube, Adobe, and Apple iTunes are all backing this cross-platform format.
• H.264 standard is jointly maintained with MPEG so that they have identical technical content.
• The intention behind H.264/AVC project was to provide good video quality at substantially lower bit rates than previous standards. An additional goal was to provide enough flexibility to allow the standard to be applied to a wide variety of applications on a wide variety of networks and systems.
• H.264/AVC/MPEG-4 Part 10 contains Multi-picture inter-picture prediction including the features like using previously-encoded pictures as references in a more flexible way than in past standards, allowing up to 32 reference pictures to be used sometimes.
• H.264 provides quarter-pixel precision for motion compensation enables very precise description of the displacements of moving areas. For chroma the resolution is typically halved both vertically and horizontally, therefore the motion compensation of chroma uses one-eighth chroma pixel grid units.
• H.264 provides six-tap filtering for derivation of half-pel luma sample predictions, to lessen the aliasing and eventually provide sharper images.
• H.264 provides flexible interlaced-scan video coding features, includes Macro block-adaptive frame-field (MBAFF) coding, using a macroblock pair structure for pictures coded as frames, allowing 16×16 macroblocks in field mode compared with 16×8 half-macroblocks in MPEG-2. An enhanced lossless macroblock representation mode allowing perfect representation of specific regions while ordinarily using substantially fewer bits than the PCM mode. Picture-adaptive frame-field coding, allowing a freely-selected mixture of pictures coded as MBAFF frames with pictures coded as individual single fields (half frames) of interlaced video.
• H.264 is more attractive for video network delivery and for delivery of HD, high definition video.
• H.264 or AVC is an open format with published specification and is available for anyone to implement.
Monday, January 18, 2010
Two-way data binding-- By Eugene Kardash
01.xml version="1.0" encoding="utf-8"?>02.<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="1024" minHeight="768">03. 04. <mx:String id="myName"/>05. <mx:Binding source="nameInput.text" destination="myName" />06. 07. <mx:TextInput id="nameInput" x="30" y="28"/>08. <mx:Label x="31" y="68" text="{myName}"/>09. 10.mx:Application>In Flex 4 this can be archived much easier, inline using declaration: @{bindable_property}. Code example:
01.xml version="1.0" encoding="utf-8"?>02.<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"03. xmlns:s="library://ns.adobe.com/flex/spark"04. xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768">05. <fx:Declarations>06. <fx:String id="myName"/>07. fx:Declarations>08. 09. <s:VGroup width="200" height="67" x="37" y="38">10. <s:TextInput id="nameInput" text="@{myName}"/>11. <mx:Spacer height="10"/>12. <s:SimpleText text="{myName}"/>13. s:VGroup>14. 15.s:Application>Monday, December 14, 2009
5 Features of Flex Builer 4
Feature 1: Generation of accessor functions
Software development can be tedious. Many applications follow the same coding practices and patterns, and developers frequently spend lots of time on repetitive coding tasks—time that could otherwise be spent implementing more interesting logic. For Flash Builder 4 beta, we targeted a number of these common coding tasks and delivered ways to get them done quickly.
The task that developers most often asked us to automate was the creation of accessor functions. Developers wanted a way to generate getter and setter methods, which comprise a public interface to access private class members. With Flash Builder 4 beta, you can create these functions by simply placing your cursor on a class variable name and choosing Source > Generate Getter/Setter from either the main menu or the context menu. You can use the Generate Getter/Setter dialog box that opens to configure details about the accessor functions, and there’s even an option to preview the changes that Flash Builder 4 beta will make to your code (see Figure 1).
Figure 1. A preview of the code generated by the new getter/setter feature
Feature 2: Event code generation
Another common developer request is for generating event code. This feature is helpful both for experienced Flex developers looking to spend less time on tedious coding and for beginners unfamiliar with event-based development. For example, developers with a background in procedural web scripting technologies—like PHP or ColdFusion—may have never needed to implement an event listener to handle an event, such as a button being clicked. Flash Builder 4 beta can automatically generate the event handler functions for a UI object from the Flex Properties view, the context menu for an item in Design view, or with content assist for an item in Code view.
Each UI item, including buttons, lists, scrollbars, and so on, has a default event. A Button, for example, has the click event. If you select a button in Design view and right—click, you will see a context menu option Generate Click Handler. Likewise, the Property Inspector will show a field labeled “on click” and a button to generate the event. Of course, you can generate event handlers for all events of a UI item by selecting Show All Events in the context menu or by expanding the Events node for the item in the Property Inspector. Once you generate an event handler, Flash Builder 4 beta generates a unique name for the event handler based on the object’s class name, properties, or a custom name you specify. The event handler is placed in the first script block of the file and you will be taken to that position in Code view. If you’re starting in Code view, you can also generate events for components. Place your cursor in a closed component tag and open content assist for the properties of the component by typing a space after the class name. The list of properties displayed includes events (for example, Click). Select an event and then select Generate Event Handler.
If you’re new to ActionScript and event—driven programming, the event code generation feature can help you learn the basics of connecting component events to methods. If you’re an experienced Flex developer, the feature can save you time by quickly generating stubs for all of your event functions.
Feature 3:Command—line builds
Many customers told us that as their Flex projects have grown in complexity, the need for Flex to fit into their enterprise development processes and systems has become more acute. One of the most common requests we heard from these customers was for a way to add Flex applications to nightly automated build processes. Unfortunately, previous versions made it difficult to synchronize a developer’s individual build settings with the nightly build. Flash Builder 4 beta solves this with the new
Command line builds can be used even if Flash Builder 4 beta is not installed on the nightly build machine. If Flash Builder 4 beta is present, the
Feature 4: Debugger enhancements
Having a full featured debugger is one of the great benefits of an integrated development environment. Flex Builder 3 has excellent debugging capabilities, but there were still many additional features and enhancements for which you’ve been asking. So for Flash Builder 4 beta, we’ve invested heavily in taking the debugger to the next level.
Sometimes, you may need to stop the debugger from executing when specific conditions are met. With Flash Builder 4 beta, you can use expressions to define these conditional breakpoints to halt execution when the expression evaluates to true, when the value of the expression changes, or when a specified hit count has been reached. Evaluation of watch expressions has also been enhanced in this release. You can use the Expressions view to watch variables you selected in the Variables view, as well as to add and evaluate watch expressions while debugging your applications.
When debugging an application, you may want to know when specific instances of variables change value. Flash Builder 4 beta allows this with a new feature called watchpoints. You set a watchpoint on a specific instance of a variable from the Variables view during a debugging session, and execution will be halted when the watched variable changes value.
Finally, if you have ever set a debugger breakpoint within a loop that repeats many times, you’ll appreciate the new run—to—line command, which can be used to break out of a loop during a debugging session.
Feature 5: Network Monitor
Nearly all Flex applications exchange data with a server or service of some sort. The requests and responses move back and forth between the client and server in different formats depending on the technique that you use as a developer. In Flex 3 you have little insight into what’s happening as the exchange occurs, no matter what technique you use. You can debug your Flex application and see what remote call is made, but then you have to wait and see what (if anything) comes back from the server. Likewise, you can debug your server—side logic, but it’s difficult to know what happens to the data once you send it back to Flex. Monitoring the actual network traffic—the requests and response data—has not been possible with Flex Builder.
Flash Builder 4 beta introduces the Network Monitor, a tool that you can use to examine the SOAP, AMF, Remote Object, XML, and HTTP traffic that flows between your Flex application and its data service or services. Now you have a simple view, active when you’re in the Debugging perspective, that provides extensive monitoring and debugging information to make building data—centric applications much easier.
To begin, click the Enable Network Monitor icon on the Network Monitor toolbar and then run the debug version of the application as you would normally. As you interact with your application, the Network Monitor captures and stores all calls to remote services in chronological order. At any time, you can switch back to the Network Monitor view to see the results of each call. The results from calls to each remote service are presented in a table listing the time of the request, the requesting service, the operation and URL (if applicable), the time of the response, and the elapsed time. You can also examine the response, including the actual data sent back. You can analyze this information as the application is running, or you can click the Save icon to write all captured information to an XML file for later analysis.
Friday, November 27, 2009
Silverlight
Silverlight is a cross-browser, cross-platform and cross-device browser plug-in that helps companies design, develop and deliver applications and experiences on the Web. Silverlight enables a new class of rich, secure and scalable cross-platform experiences.
Silverlight 3 introduces major media enhancements, out of browser support allowing Web applications to work on the desktop; significant graphics improvements including perspective 3D graphics support, GPU acceleration and H.264 video support; and many features to improve RIA development productivity. To fully integrate all the .NET developer tools, Visual Studio 2008, Visual Studio 2010 and Visual Web Developer Express support a fully editable and interactive designer for Silverlight.
Silverlight include:
Support for Higher Quality Video & Audio
Empowering Richer Experiences
Improving Rich Internet Application Productivity
Enhanced Data Support
Improved performance
Out of Browser Capabilities
Monday, September 14, 2009
Scala-- The Future of java is here!!
Scala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala is designed to integrate easily with applications that run on modern virtual machines, primarily the Java virtual machine (JVM). The main Scala compiler, scalac, generates Java class files that can be run on the JVM. However, another Scala compiler exists that generates binaries that can be run on the .NET CLR, as Scala is designed to integrate with both the Java and .NET worlds. In the Java world, the Scala language can be used alongside the Java language—either as an alternative to Java—to build applications that run on the JVM.
Scala was developed starting in 2003 by Martin Odersky's group at EPFL, Lausanne, Switzerland. Previously, Martin had been active in the Java field. He co-designed the first version of Java generics and was the original author of the current javac compiler. The work on Scala was motivated by the desire to overcome limitations imposed by backwards compatibility with Java. So Scala is not a superset of Java, but it retains seamless interoperability.
One reason you might want to use Scala is that it allows you to increase your productivity compared to Java while leveraging JVM execution speed, your existing investments in Java code, knowledge, and the vast array of APIs available for the JVM. It has the conciseness of a dynamic language like Ruby or Python, but it is statically typed, like Java. Another reason is that Scala comes with an Erlang-like Actors library that greatly simplifies concurrent programming, but runs on the JVM.
By: http://www.artima.com/scalazine/articles/steps.html
Wednesday, September 9, 2009
Mashups
Mashups
In the context of learning and assessments mashups can be categorized as follows:
- Portlet – configured by an end user
- Page (Web, Wiki or Blog) – configured by a web author
- Data – configured by a programmer
Portlet Based Mashup
Portlet based mashups provide different “windows” that interact with different and separate applications and users can move these portlets around their screen to meet their own personal requirements.
Page Based Mashup
Page based mashups are configured by the author of the web page, wiki and or blog to determine where application data and interactions might occur.
Documentation, learning content and assessments are often available throughout an organization’s infrastructure but challenging to find and they are especially difficult to find in context. Wikis, blogs and web pages can be used to expose existing resources, wrap context, to provide a meaningful learning and/or assessment experience. Learning mashups can improve learner experiences and learning outcomes.
Data Mashups
A data mash up is where data is drawn from different data sources and displayed within a single page. In this style a programmer constructs a program to retrieve the data, from different data sources, and then display it within a web page.
Courtesy- http://www.linkedin.com/news?viewArticle=&articleID=66406667&gid=55108&articleURL=http%3A%2F%2Fblog.eric.info%2F2009%2F09%2F01%2Flearning-mashups%2F&urlhash=tz-h&trk=news_discuss
Monday, September 7, 2009
Load balancing FMS servers using LVS (DR mode)
How do we configure LVS (or any load balancer for that matter) to detect when there has been a failure of a particular real server?
Answer by Jean--
It is possible to load balance using LVS, we could do an HTTP health monitor against FMS since it supports tunneling over HTTP. We can also probably hit the admin service port of the FMS server, which has a REST like interface and use some metrics like the number of streams or number of application instances. keep alived or something similar should work for the actual interface for putting servers in an out of rotation for local server load balancing. People generally know who use LVS write their own custom health check layer.
Monday, August 31, 2009
Flex Ajax Bridge
Flex Ajax Bridge
The Flex Ajax Bridge (FABridge) is a small code library that you can insert into an Flex application, a Flex component, or an empty SWF file to expose it to scripting in the browser.
Rather than having to define new, simplified APIs to expose a graph of ActionScript objects to JavaScript, with FABridge you can make your ActionScript classes available to JavaScript without any additional coding. After you insert the library, essentially anything you can do with ActionScript, you can do with JavaScript.
Adobe Flash Player has the native ability, through the External API (the ExternalInterface class), to call JavaScript from ActionScript, and vice versa. But ExternalInterface has some limitations:
- The ExternalInterface class requires you, the developer, to write a library of extra code in both ActionScript and JavaScript, to expose the functionality of your Flex application to JavaScript, and vice versa.
- The ExternalInterface class also limits what you can pass across the gap - primitive types, arrays, and simple objects are legal, but user-defined classes, with associated properties and methods, are off-limits.
- The ExternalInterface class lets you define an interface so your JavaScript can call your ActionScript. FABridge lets you write JavaScript instead of ActionScript.
When to use the Flex Ajax Bridge
The FABridge library is useful in the following situations:
- You want to use a rich Flex component in an Ajax application but do not want to write a lot of Flex code. If you wrap the component in a FABridge-enabled stub application, you can script it entirely from JavaScript, including using JavaScript generated remotely by the server.
- You have only one or two people on your team who know Flex. The FABridge library lets everyone on your team use the work produced by one or two Flex specialists.
- You are building an integrated rich Internet application (RIA) with Flex and Ajax portions.Although you could build the integration yourself using ExternalInterface, you might find it faster to start with the FABridge.
Requirements for using the Ajax Bridge
To use the FABridge library and samples, you must have the following:
- Flex Ajax Bridge, which is included in the following directory of the Flex 3 SDK installation:
installation_dir\frameworks\javascript\fabridge
- Adobe Flex SDK
- Adobe® Flash® Player 9 or Adobe® AIR™
- Microsoft Internet Explorer, Mozilla Firefox, or Opera with JavaScript enabled
- Any HTTP server to run the samples
To run the samples:
- Browse to the files found within the installation_dir\frameworks\javascript\fabridge
- Place the src and samples folders side by side on any HTTP server.
- Open a web browser to http://yourwebserver/samples/FABridgeSample.html and samples/SimpleSample.html and follow the instructions there. Make sure you access the samples through http:// URLs and not file:// URLs. The Flash Player security sandbox prevents them from working correctly when they are accessed as local files.
Sunday, August 9, 2009
Local Shared Object
LSO, a bigger better cookie
Local Shared Object (LSO) or Flash cookie, like the HTTP cookie, is a way of storing information about us and tracking our movement around the Internet. Some other things I learned:
- Flash cookies can hold a lot more data, up to 100 Kilobytes. A standard HTTP cookie is only 4 Kilobytes.
- Flash cookies have no expiration date by default.
- Flash cookies are stored in different locations, making them difficult to find.
The only way you can access information about resident Flash cookies is by going to Flash Player’s Web site.
Courtesy- http://blogs.techrepublic.com.com/security/?p=2299&tag=nl.e036
Wednesday, August 5, 2009
DTO (Data Transfer Objects)
A Data Transfer Object, or DTO is a design pattern for a very specific type of object that is used to transfer data between different parts of your application.
A DTO is just for temporarily storing information whilst it is in transit. Therefor a DTO has limited behaviour, only that of storing, retrieving, validating, and internal consistency checking of its own data. They should have no responsibility in terms of security, transaction, and business logic. This de-coupling of storage and business logic will enable us to use the same DTO in different contexts.
DTOs come in two different types: generic collections, or custom objects.
Generic Collections
Generic collections, eg. Dictionaries or Arrays, are advantageous in that you only require a single DTO for all your data transfer needs. The main disadvantage is that the client has to access fields either by position index (in the case of Arrays), or by key (in the case of Dictionaries). A further problem is that as the type of objects in a collection is unknown. In a future revision of Actionscript Arrays will be typed, which will only allow collections to store data of one type. This can lead to items being stored as a generic Object type, which can lead to subtle but fatal coding errors that cannot be detected at compile time.
The creation of a dynamic generic objects can be costly as Flash doesn’t know how much memory to allocate. By typing all your variables, Flash can then allocate the necessary memory for those variables and no more. This avoids the creation of a Hash Table and will therefor decrease memory consumption and increase performance.
Custom Objects
Creating a custom class for your DTOs provides strictly typed objects which allow for compile-time checking and support code editing features like FDTs “code assist” feature (ctrl + space). The only drawback is the creation of a large amount of DTOs that might be required for a large application.
Fields contained within a custom DTO should be of primitive/simple types eg. strings, booleans, etc. or arrays of those, and it may even contain other DTOs. As DTOs are meant to be temporary objects for transferring data, their fields should be immutable (read-only). Although this can be particularly difficult to achieve under certain circumstances.
- package ch.forea.exampleDTO {
- public class CardDTO{
- private var _name:String;
- private var _address:String;
- private var _phone:String;
- public function CardDTO(name:String, address:String, phone:String){
- _name = name;
- _address = address;
- _phone = phone;
- }
- public function get name():String{
- return _name;
- }
- public function get address():String{
- return _address;
- }
- public function get phone():String{
- return _phone;
- }
- }
- }
The purpose of all this is to package all required information in to one package, therefor transferring everything in one call rather than multiple calls. This method can be advantageous if the call is to a remote system, as any further calls to the DTO are made locally to the client.
http://forea.ch/blog/2008/11/14/back-to-basics-the-data-transfer-object-dto/
Tuesday, August 4, 2009
ApplicationDomain class
Using the ApplicationDomain class
The purpose of the ApplicationDomain class is to store a table of ActionScript 3.0 definitions. All code in a SWF file is defined to exist in an application domain. You use application domains to partition classes that are in the same security domain. This allows multiple definitions of the same class to exist and also lets children reuse parent definitions.
You can use application domains when loading an external SWF file written in ActionScript 3.0 using the Loader class API. (Note that you cannot use application domains when loading an image or SWF file written in ActionScript 1.0 or ActionScript 2.0.) All ActionScript 3.0 definitions contained in the loaded class are stored in the application domain. When loading the SWF file, you can specify that the file be included in the same application domain as that of the Loader object, by setting the applicationDomain parameter of the LoaderContext object to ApplicationDomain.currentDomain. By putting the loaded SWF file in the same application domain, you can access its classes directly. This can be useful if you are loading a SWF file that contains embedded media, which you can access via their associated class names, or if you want to access the loaded SWF file's methods, as shown in the following example:
package {
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class ApplicationDomainExample extends Sprite {
private var ldr:Loader;
public function ApplicationDomainExample() {
ldr = new Loader();
var req:URLRequest = new URLRequest("Greeter.swf");
var ldrContext:LoaderContext = new LoaderContext(false,
ApplicationDomain.currentDomain);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
ldr.load(req, ldrContext); }
private function completeHandler(event:Event):void {
ApplicationDomain.currentDomain.getDefinition("Greeter");
var myGreeter:Greeter = Greeter(event.target.content);
var message:String = myGreeter.welcome("Tommy");
trace(message); // Hello, Tommy } } }
Using the ApplicationDomain class Other things to keep in mind when you work with application domains include
the following:
- All code in a SWF file is defined to exist in an application domain.
The current domain is where your main application runs.
The system domain contains all application domains, including the current
domain, which means that it contains all Flash Player classes. - All application domains, except the system domain, have an associated parent
domain. The parent domain for your main application's application domain is
the system domain. Loaded classes are defined only when their parent doesn't
already define them. You cannot override a loaded class definition with
a newer definition.
YOUR EPITAPH
YOUR EPITAPH
I've got whole worlds staring at screens
And yet no one ever senses me in between.
I could be any of the ones or the zeros
One of its zillion unsung heroes
I'm told I'm a geek god in a glass temple
Worshipped. Overpaid. Replaceable.
A human architect in this digital crucible,
Neo, Invincible, One, Invisible.
I exist, God-like in a desk job mode
And on the 7th day I rest
I can be benched, right sized or dropped on the road
Never lived for, though I too will live forever with the index
So my friend, if you, like myself, are seeking me now
I pray this song finds you somehow.
Coz my world is so much smaller these days
So small, precious little is face to face
And if I've earned one epitaph no one grudges me,
It's for being human, behind the screen
For putting the ones and zeros in place
And most of myself in this digital embrace
You see the world is so much smaller these days
How could something so small take away my face?
Sunday, August 2, 2009
Domain Specific Languages (DSLs)
Thursday, July 30, 2009
Adobe Stratus
What is Adobe Stratus?
With Flash Player 10, Adobe brought in enhancements that make writing P2P applications a reality. Flash Player 10 provides support now for a new protocol called Real Time Message Flow Protocol (RTMFP). This protocol is well suited to creating applications that need to communicate to each other directly. This communication is facilitated via the Adobe Stratus Service which supports the RTMFP protocol and is a rendezvous Hosted Service that facilitates connection between two Flash Player 10 instances.
Once the Flash Player 10 instances are connected to each other, the two applications can continue to talk to each other without going through an intermediate server side.
Adobe has had Flash Media Server (FMS) over the years and recently they have also introduced Adobe Flash Collaboration Services (AFCS), formerly known as Cocomo. FMS currently does not support the RTMFP protocol but future versions of it could. On the other hand, Adobe Stratus in conjunction with the Flash Player 10 APIs does not provide support for full P2P capabilities like relay, shared data models, etc. but depending on the kind of application that you may require, it might just about the fit the requirements of your P2P Application without requiring additional server side architecture.
Plz refer
http://www.linkedin.com/news?viewArticle=&articleID=54537631&gid=113435&articleURL=http%3A%2F%2Fwww.insideria.com%2F2009%2F07%2Fgetting-started-with-adobe-str.html&urlhash=LoE9&trk=news_discuss
Sunday, June 28, 2009
Silex-- A new Approach
Friday, June 19, 2009
USB 3.0
USB 3.0 specifications were announced in November by Intel and Intel developer Sarah Sharp has been busy coding the linux drivers ever since. The drivers have been ready and have been scheduled to be merged with the Linux mainstream kernel in the version 2.6.31. Traditionally it has always been that Windows is the first OS to get the hardware drivers and the linux geeks tend to reverse engineer or design it based on the specification but this time around tables have been turned over.
The support of Intel to mainstream linux and to the development of open hardware drivers does seem to be a road of change on the part of the hardware manufacturers who have traditionally been windows centric.
The USB 3.0 hardwares have not made to the market yet although NEC is producing 1 million xHCI PCI-Express add-in cards for september release.
Sarah is also working to ensure that these drivers make it to mainstream distributions like Redhat and Ubuntu, according to the post on her blog.
For those who do not know USB 3.0 specification gives a 10x increase over the existing USB standard delivering a transfer rate of 5.0Gbps. You can read further details here: http://en.wikipedia.org/wiki/
For those who live on the edge and want to test out the drivers(in case you are the lucky few with the hardware), head on to The Geekess blog at http://sarah.thesharps.us/
Monday, June 15, 2009
Adobe Flash Collaboration Service aka Cocomo
AFCS (Adobe Flash Collaboration Service) previously known as 'Cocomo' is a Platform as a Service (PaaS) that that allows Flex developers to address a class of applications known as collaborative applications.
Collaborative Applications have progressed from a nice cool thing into serious applications. Almost all of us would have participated in an online chat or a web meeting, which allows a group of users to chat, share files, do screen sharing, take polls, ask questions and receive answers, etc. AFCS aims to lower the barrier to entry for developers to bring such collaborative features into their applications.
A developer would have general questions like:- Why do we need a set of components to enable collaborative features in my application?
- It should not be that complex to build a collaborative application, right? Isn't chat and sharing some files the maximum that I would want?
- …and many more.
- Handle Audio, Video and all other forms of transcoding data
- Ensure that your application can scale to a large number of users.
- Enable shared state in your application and ensure that multiple users are co-coordinated with each other so maintain data integrity
- Reuse commonly used components like chat, notes, whiteboard, etc so that you can build the applications quickly and not reinvent the wheel.
- Handle User Management and Permissions
Courtesy-- TechRepublic!!!!!!!!!!!!!!!
Thursday, June 11, 2009
Multiple Inheritance in Java and Delegate Factory pattern
When Sun was designing Java, it omitted multiple inheritance - or more precisely multiple implementation inheritance - on purpose. Yet multiple inheritance can be useful, particularly when the potential ancestors of a class have orthogonal concerns. This article presents a utility class that not only allows multiple inheritance to be simulated, but also has other far-reaching applications.
Have you ever found yourself wanting to write something similar to:
public class Employee extends Person, Employment {
// detail omitted
}
Here, Person is a concrete class that represents a person, while Employment is another concrete class that represents the details of a person who is employed. If you could only put them together, you would have everything necessary to define and implement an Employee class. Except in Java - you can't. Inheriting implementation from more than one superclass - multiple implementation inheritance - is not a feature of the language. Java allows a class to have a single superclass and no more.
On the other hand, a class can implement multiple interfaces. In other words, Java supports multiple interface inheritance. Suppose the PersonLike interface is:
public interface PersonLike {
String getName();
int getAge();
}
and the EmployeeLike interface is:
public interface EmployeeLike {
float getSalary();
java.util.Date getHireDate();
}
If Person implements the Person-Like interface, and Employment implements an EmployeeLike interface, it's perfectly acceptable to write:
public class Employee implements PersonLike, EmployeeLike {
// detail omitted
}
Here there is no explicit superclass. Since we are allowed to specify at most one superclass, we could also write:
public class Employee extends Person implements PersonLike, EmployeeLike {
// detail omitted
}
We would need to write the implementation of EmployeeLike, but the implementation of PersonLike is taken care of through the Person superclass. Alternatively we might write:
public class Employee extends Employment implements PersonLike, EmployeeLike{
// detail omitted
}
This is the opposite situation: the EmployeeLike interface is taken care of through the Employment superclass, but we do need to write an implementation for PersonLike.
Java does not support multiple implementation inheritance, but does support multiple interface inheritance. When you read or overhear someone remark that Java does not support multiple inheritance, what is actually meant is that it does not support multiple implementation inheritance.
Stay Adaptable
Suppose then that you have the concrete implementations Person, which implements the PersonLike interface, and Employment, which implements the EmployeeLike interface. Although only one can be selected to be the superclass, it would be useful to somehow exploit the other implementation.
The easiest way to do this in Java is by applying the (Object) Adapter pattern. If we make Person the superclass, we can use Employment using an object adapter held within the employee:
public class Employee extends Person implements PersonLike, EmployeeLike {
private EmployeeLike employment = new
Employment();
public float getSalary() { return
employment.getSalary(); }
public java.util.Date getHireDate() { return employment.getHireDate(); }
}
For each method of EmployeeLike, the employee delegates to the object adapter. This helps motivate the decision as to whether Person or Employment should be the superclass; choose the one with the most methods as the superclass so there will be less manual delegation code to write when dealing with the other interface.
The Adapter pattern is a fine way to support multiple interface inheritance while exploiting two concrete implementations. Indeed, it's more often the case that an anonymous inner class is used as the object adapter, allowing customization of behavior with respect to the context (of being embedded within a subclass).
However, writing that delegation code is tedious, especially if both interfaces to be implemented have many methods in them. In many cases, we can get Java to do the delegation to the would-be superclass(es) automatically.
Enter Dynamic Proxies
Dynamic proxies were introduced into Java in J2SE v1.3. Part of the java.lang.reflect package, they allow Java to synthesize a class at runtime. The methods supported by this synthesized class are specified by the interface (or interfaces) that it implements. The implementation is taken care of through an invocation handler (java.lang.reflect.InvocationHandler) that is handed an object representing the method being invoked (java.lang. reflect.Method). As you can see, dynamic proxies use heavy doses of the Java Reflection API.
This then is the key to simulating multiple implementation inheritance within Java. We can write a custom InvocationHandler that is constructed with a set of classes; these represent the superclasses of the subclass to be synthesized. The interface(s) of our subclass will be the union of the interfaces implemented by these superclasses. Our InvocationHandler will instantiate instances of these superclasses so that it can delegate to them. We then arrange it so that the invocation handler, on being given a method to be invoked, will reflectively invoke the method on the appropriate superclass object instance. (There must be one; remember the subclass's interface is derived from the superclass's, so at least one superclass must be able to handle the method invocation.)
To make things simple, we can make our InvocationHandler implementation also return the proxy. In other words, the invocation handler can act as a factory, able to return instance(s) of the synthesized subclass that will delegate to the superclass instances. We call our invocation handler implementation DelegatorFactory for this reason:
// imports omitted
public final class DelegatorFactory
implements InvocationHandler {
public Object getObject() {
return Proxy.newProxyInstance(
this.getClass().getClassLoader(),
getSupportedInterfaces(),
this);
}
}
// code omitted
}
The supported interfaces of the resultant object are derived from the superclasses provided in the DelegatorFactory's constructor:
// imports omitted
public final class DelegatorFactory implements InvocationHandler {
public DelegatorFactory(final Class[]
ancestors) {
// implementation omitted
}
// code omitted
}
There is more to DelegatorFactory as we shall soon see, but we now have enough to simulate multiple implementation inheritance. Going back to the question first posed, instead of:
public class Employee extends Person, Employment {
// detail omitted
}
followed (presumably) by:
Employee employee = new Employee();
We can instead write:
Object employee =
new DelgatorFactory(
new Class[] {
Person.class,
Employee.class
}
).getObject();
Although the syntax is somewhat different, the same essential information is being provided. That is, the concrete implementations are provided in Person and in Employment. This object will use the implementation of Person if invoked as a PersonLike, and the implementation of Employment if invoked as an EmployeeLike:
((PersonLike)employee).getAge();
((EmployableLike)employee).getHireDate();
How Convenient
In the above example, the casts are necessary because the getObject() method of DelegatorFactory can only return a reference of type java.lang.Object. But the clunkiness arises because our original aim of defining the Employee class with two concrete superclasses actually does something else as well:
public class Employee extends Person, Employment {
// detail omitted
}
Not only does this indicate that the implementation of Employee should be based on that of its superclasses, it also defines Employee as a type. In other words, it's then possible to write:
Employee employee;
What is missing in our dynamic proxy solution is this definition of type. Let's first do that in the usual way. As shown in Figure 2, we don't need to use a class though; an interface is sufficient.
As code, this is simply:
public interface Employee extends PersonLike, EmployeeLike { }
There is no detail omitted here; this is our complete definition. Note that Employee is now an interface and not a class. The following will not work, however:
Employee employee =
(Employee)
new DelegatorFactory(
new Class[] {
Person.class,
Employment.class
}
).getObject();
This is because the only interfaces implemented by the dynamic proxy returned by getObject() are PersonLike and EmployableLike. No matter that logically the Employee interface does not require any additional implementation from our dynamically created object; Employee is not an interface that we can cast to. However, DelegatorFactory does provide an alternative constructor:
Employee employee =
(Employee)
new DelegatorFactory(
new Class[] {
Person.class,
Employment.class
},
Employee.class
).getObject();
Note the new second argument (Employee.class) to the constructor. Casting the object returned from getObject() to Employee will now work. Behind the scenes, the Delegator- Factory simply adds this interface to the set of those to be implemented by the dynamic proxy. Note that Delegator Factory takes this interface object on trust: there is no validation that the interface doesn't introduce any new methods that are not already present in the interfaces of the superclasses.
Initializing the Superclasses
In "regular" Java, if a superclass does not provide a no-arg constructor, it's necessary for the subclass to correctly initialize the superclass using constructor chaining. Normally this is done by including the superclass's constructor's argument(s) in the subclass's constructor's argument(s), and then passing them up the class hierarchy using super().
The facilities shown in Delegator-Factory thus far do not support this. The DelegatorFactory is given a list of superclasses, and then instantiates an instance of each (to delegate to) using java.lang.Class.newInstance(). This requires a public no-arg constructor to exist.
If the would-be superclass does not offer a public no-arg constructor, the DelegatorFactory should be instantiated using a different constructor that takes preinstantiated superclass instances:
Person person = new Person("joe", 28);
Employment employment =
new Employment(someCalendar.getTime(),
30000);
Employee employee =
(Employee)
new DelegatorFactory(
new Object[] {
person, employment
},
Employee.class
).getObject();
If the would-be superclass does not have a public constructor, or is abstract, a custom subclass (probably an anonymous inner class) should be instantiated and used instead.
Dealing with Diamonds
Typically, multiple implementation inheritance is used when the superclasses have orthogonal concerns. Certainly this is the case with PersonLike and EmployeeLike, and each method is unambiguous as to which ancestor it relates to.
However, sometimes there may be a common super-interface in the interfaces implemented by the "superclasses." For example, suppose we have the concrete class, Car, which implements Driveable, the Boat class, which implements Sailable, and both Driveable and Sailable extend from Steerable. Since we want to use both Car and Boat to define a new subclass, we will also introduce a convenience interface, AmphibiousCar (see Figure 3).
The steer() method of Steerable is used to alter the bearing (0 to 359 degrees) of the steerable object. The getBearing() method, of course, should return this bearing.
For simplicity, the drive() method of Driveable and the sail() method of Sailable return a suitable string indicating the current bearing. Invoking drive() might return a string such as:
driving at bearing 30 degrees.
From what we currently know, we would create an amphibious car object using:
AmphibiousCar ac =
(AmphibiousCar)
new DelegatorFactory(
Class[] {
Car.class, Boat.class
}).getObject();
What happens if we invoke the steer() method on our new amphibious car ac? Should the invocation handler delegate to the Car superclass object or the Boat? The default behavior is to delegate to the first matching object. Hence, we will get:
ac.steer(30);
System.out.println(ac.drive());
// prints "driving at bearing 30 degrees"
System.out.println(ac.sail());
// prints "sailing at bearing 0 degrees"
The Boat superclass component of our class never knew that the bearing had changed.
It's this kind of problem that persuaded the Java language designers to exclude multiple implementation inheritance. This is too large an area to cover in this article, but what we have here is an example of part of the so-called "diamond" problem, where there is a common ancestor. You can see the diamond in the interfaces: Steerable, Driveable, Sailable, and Amphibious-Car.
The DelegatorFactory utility deals with the diamond problem by allowing you to specify the invocation behavior to the delegate superclasses as a pluggable strategy (an example of the Strategy pattern). The strategy is defined by the InvocationStrategy interface. The default strategy (InvokeFirstOnlyStrategy) is to invoke the first ancestor superclass that can handle the method. However, in the case of the diamond, what is required is that both ancestors need to handle the method. The InvokeAllStrategy handles this. If the method being invoked has a nonvoid return type, the return value from the first ancestor is returned. The two strategies are shown in Figure 4.
The invocation strategy can either be set after the DelegatorFactory has been instantiated, or can be set through (yet another) overloaded constructor. Hence our amphibious car should be created using:
AmphibiousCar ac =
(AmphibiousCar)
new DelegatorFactory(
Class[] {
Car.class, Boat.class
},
new InvokeAllStrategy()
).getObject();
This time, we get:
ac.steer(30);
System.out.println(ac.drive());
// prints "driving at bearing 30 degrees"
System.out.println(ac.sail());
// prints "sailing at bearing 30 degrees"
The InvokeFirstOnlyStrategy and InvokeAllStrategy are not the only strategies available (indeed we shall see one more shortly); however, they should work for most situations.
If a custom invocation strategy is required, it can be written by implementing the InvocationStrategy interface:
public interface InvocationStrategy {
Object invoke(final List ancestors,
final Method method,
final Object[] args)
throws Throwable
}
The ancestors parameter is an immutable list of the object instances representing the superclass. The method parameter represents the Method being invoked, and the args parameter contains the arguments to that Method. A typical invocation strategy would likely call method.invoke(S) somewhere within its implementation, with the first argument (the object upon which to invoke the method) being one of the ancestors.
We shall look at some applications of custom invocation strategies shortly. For now, though, an adaptation of InvokeAllStrategy might be to return the average return value of all ancestors, not just the return value of the first one.
Implicit Diamonds
In the previous diamond example, the Steerable interface is explicitly a super-interface of both Driveable and Sailable. What if the super-interface has not been explicitly factored out, though?
For example, in the original PersonLike and EmployeeLike example, what if each provided a foo() method, returning a string. Not imaginative, but never mind. Let's construct our employee and use an InvokeAllStrategy:
Employee employee = (Employee)
new DelegatorFactory(new Class[]{Person.class, Employment.class},
Employee.class,
new InvokeAllStrategy())
.getObject();
Now let us invoke foo():
employee.foo(); // what will happen?
Should the Person's implementation be called, that of Employment, or both? Although you might wish that both would be called (by virtue of our installed strategy), the sad truth is that only Person's implementation would be called. This is because the dynamic proxy has no way of knowing which interface to match foo() to, so it simply matches it to the first interface listed. (It's a java.lang.reflect.Method that is passed to the DelegatorFactory, not the string literal "foo()". Methods are associated with a specific declaring class/interface.) In terms of the DelegatorFactory's implementation, this means the first superclass listed in its constructor.
Note also that the compile time type does not matter. Neither of the following will change the outcome:
((PersonLike)employee).foo(); ((EmployeeLike)employee).foo();
In fact, it would be possible to modify DelegatorFactory to make Invoke-AllStrategy effective in this case, but that would involve parsing on the Method.getName() rather than the method. However, this has deliberately not been done. We'd rather you factored out the super-interface and made the diamond explicit. In the above example, add a FooLike (or Fooable) interface and make both PersonLike and EmployLike extend from it.
Other Applications
The issue raised by diamonds (implicit or otherwise) is that of how to deal with more than one implementation of a given method within an interface. However, it's interesting to turn this on its head.
In aircraft and other safety-critical environments, it's common to implement subsystems in triplicate. For example, there may be three different navigational systems, possibly with each implemented by different subcontractors. Each of these would be able to respond to the request, "Where is the location of the aircraft?"
Other systems within the aircraft interact with the navigational subsystem through a broker. This accepts the request on behalf of the navigational subsystem, and then forwards the request onto each implementation. Assuming there are no bugs in any of those implementations, they should all respond with the same data (within some delta of acceptable variance).
If there is a bug in one of the implementations, it may produce a response that differs wildly from the other two implementations. In this case, the broker disregards that response completely and uses the responses of the other implementations that agree with each other.
The design of DelegatorFactory and its pluggable invocation strategies make it easy to implement such a broker. Imagine a Calculator interface that defines a single method add(int, int):int. We can then have three implementations of this interface, as shown in Figure 5.
The FastCalculator uses regular integer arithmetic. The OneByOne- Calculator rather long-windedly performs its arithmetic by incrementing the first operand one-by-one in a loop. Both of these implementations are correct, just different. The final BrokenCalculator is just that; it actually performs a subtraction, not an addition.
The InvokeSafelyStrategy invocation strategy requires at least three ancestors that implement each method invoked. It will invoke the method on all ancestors, and then look to see that there is precisely one response that is most popular. Here is how to create a safe calculator that will ignore the incorrect implementation within the BrokenCalculator:
DelegatorFactory dfInvokeSafely =
new DelegatorFactory(
new Class[] {
BrokenCalculator.class,
OneByOneCalculator.class,
FastCalculator.class
},
Calculator.class,
new InvokeSafelyStrategy()
);
Calculator safeCalculator =
(Calculator)dfInvokeSafely.getObject();
assertEquals(7, safeCalculator.add(3,4));
Note that the InvokeSafelyStrategy is not all that intelligent. It stores the return values from each ancestor within a HashSet, so it relies on an accurate implementation of equals() and hashCode(). If the actual return type were a float (wrapped within a Float object), a more sophisticated invocation strategy would most likely be required. In general, this strategy will work only with well-defined value objects that can intrinsically deal with any rounding and other such errors.
You could easily adapt or refine the InvokeSafelyStrategy into further strategies. For example:
Moreover, there is nothing to prevent multiple invocations from being chained together, (that is, the Decorator pattern). Alternatively, we could imagine a composite strategy (the Composite pattern) that combines a set of strategies together. Either the invocation chain (decorator) or the set of leaf strategies (composite) could be changed at runtime, meaning that we can change the behavior and responsibilities of the object dynamically. This is a fundamentally different paradigm from conventional Java with its static typing. Normally, it's the type/class of the object that determines its behavior, something that cannot be changed once the object is instantiated. Here, though, we have ended up configuring the behavior of objects on an instance-by-instance basis: so-called instance-based programming. In effect, the whole notion of type becomes much less important.
There are echoes here too of aspect-oriented programming. Most aspect-oriented programming uses compile-time techniques (the term used is "weaving") to add in behavior to classes. The classic example of aspect-oriented programming is to add logging within all method calls. You can easily see, though, that these same features can be incorporated dynamically using invocation strategies; the decorator/composite invocation strategies would allow an arbitrary set of aspects to be added to a class. The difference though is that now the aspects are applied at runtime (and hence can be changed without recompile and redeployment).
Conclusion
The DelegatorFactory is simple to use, supporting classic mix-in (orthogonal) multiple-implementation inheritance "out-of-the-box" and - with its pluggable invocation strategy design - allows diamond hierarchies to be easily supported. Moreover, the design also lends itself to other quite unrelated problem spaces; for example, creating safe systems was explored. Taken to its logical conclusion, the approach supports both instance-based programming and aspect-oriented programming.
Of course, what makes DelegatorFactory work is Java's support for dynamic proxies, and that in turn requires that the ancestor superclasses implement interfaces. This approach won't work for class-based designs (JDOM is an example that comes to mind). But arguably class-based designs should be used only for value objects that should be final anyway. Those situations where multiple inheritance is desired are more likely to occur when working with reference objects.
One particular case deliberately not supported by DelegatorFactory is when there is a so-called implicit diamond. The solution though is to pull out the methods that appear in both interfaces, and move them into a new super-interface. Then, make sure you use InvokeAllStrategy rather than the default InvokeFirstOnlyStrategy.
Of course, using a dynamic proxy object will be slower than a hand-crafted solution, principally because reflection is used. However, the difference may not be noticeable in practice. In recent releases of Java, Sun has put much effort in speeding up reflective invocation; as of JDK 1.4.1, it may well be that regular invocation is only twice as fast as reflective invocation (previously this figure was something like 40 times faster).
Using DelegatorFactory
The DelegatorFactory utility class and supporting classes described here can be downloaded from www.sys-con.com/java/sourcec.cfm, and are compilable using Ant (v1.5.1 was used to create the build file). A JUnit-based test harness is also provided; JUnit v3.8.1 is required. The motivating examples in this article are based on the JUnit tests, so they should be easy enough to follow.
To run the tests with JUnit's text-based test runner, use:
ant test
Alternatively, you can use JUnit's test runner by running directly:
ant rebuild
java -classpath
dist/halware-util-dynamic-bin.jar;dist/halware-util-dynamic-bin-test.jar
com.halware.util.dynamic.test.AllTests gui
(The GUI test runner is not the default since JUnit's classloaders do not understand the Class-Path manifest attribute.)
I hope you find DelegatorFactory useful. It has been distributed under the GNU Lesser Public License, so you are free to embed it within your own software as required.