Eugene responded to my earlier post An even more capable SafeHashMap with It is safer not to invent safe hash map / Java. While he does make some valid points I did have issues with some others, the issues being Signature Instability, Compilation Troubles, Principle of Least Surprise and Style.
Eric Redmond in his post A Safe HashMap for Java describes a SafeHashMap
Here’s a suggestion to extend the capabilities of the same. Lets look at the code.
Define an interface to create an instance.
First, I create a new interface (We’ll get to know why very soon).
public interface InstanceProvider<K,V>
{
public V createNew(K k);
}
The SafeMap class itself
Here’s the proposed class. The main distinction is that instead of caching an instance and using the clone method to clone, this implementation stores away a reference to the instance provider and triggers it when required.
public class SafeMap<K, V> extends HashMap<K, V>
{
// Here's where we cache away the provider
private InstanceProvider<K,V> provider;
// Note that the provider is now
// passed to all the constructors
public SafeMap(
int initialCapacity,
float loadFactor,
InstanceProvider<K,V> provider)
{
super(initialCapacity,loadFactor);
this.provider = provider;
}
public SafeMap(
int initialCapacity,
InstanceProvider<K,V> provider)
{
this.provider = provider;
}
public SafeMap(
InstanceProvider<K,V> provider)
{
this.provider = provider;
}
public SafeMap(
Map<? extends K, ? extends V> m,
InstanceProvider<K,V> provider)
{
super(m);
this.provider = provider;
}
@Override
@SuppressWarnings("unchecked")
public V get(Object key)
{
V value = super.get(key);
if (value == null)
{
// use the provider here
value =
provider.createNew(
(K) key);
}
return value;
}
}
Test Case demonstrating usage.
public class TestSafeMap
{
@Test
public void testGetObject()
{
// Am using an anonymous class here.
// If additional parameters are required
// to be passed to constructor, one could
// create an abstract class with the constructor
// and pass the necessary arguments
Map<String, List<String>> myMap =
new SafeMap<String, List<String>>(
new InstanceProvider<String, List<String>>()
{
public List<String> createNew(String string)
{
List<String> list = new ArrayList<String>();
list.add(string);
return list;
}
}
);
String key = "hello world";
assertEquals(
"List size should've been one",
1,
myMap.get(key).size());
assertEquals(
"The only element in the list should've been : " + key,
key,
myMap.get(key).get(0));
}
@Test
public void testArrayInstantiation()
{
Map<String, String[]> myMap =
new SafeMap<String, String[]>(
new InstanceProvider<String, String[]>()
{
public String[] createNew(
String string)
{
return new String[] {string};
}
}
);
String key = "hello world";
assertEquals(
"List size should've been one",
1,
myMap.get(key).length);
assertEquals(
"The only element in the list should've been : " + key,
key,
myMap.get(key)[0]);
}
}
This way I get a finer level of control on the instantiation of the default instance. There are multiple reasons why one might want that such as :
- The default instance needs to be configured in some way depending upon the key value (shown in the example above)
- The default instance needs to be configured based on some constructor parameters passed to it. In this case create an abstract class which implements the interface, declare a constructor with the necessary arguments, use the abstract class during instantiation, and allow the createNew method to behave appropriately based on the values of the arguments.
- There are some situations such as where the type above is a String[] where the clone method does not work (as in the second test case above). Perhaps the code to conduct the cloning could be modified above to create an array, but I am not too sure (since I’ve often faced difficulties working with instantiation of array types when using generics).
Acknowledgement
There are a couple of helpful posts that set me off on the path to blog this so here’s the acknowledgement :
Introduction
I have been spending some time on the Facebook and OpenSocial platforms, and while these both attempt to solve the same need, they end up doing so quite differently. For anyone interested in web based software design, the differences are both curious and interesting, and serve an interesting contrast of how different means can get used to attempt to reach similar ends.
The Facebook platform
The facebook platform primarily allows the hosted applications to access facebook data through a variety of APIs. The hosted application can primarily draw itself onto a “Canvas” which is the primary channel of interaction, and can also render its own part of the profile, and plug into the messaging infrastructure (news feeds, mails etc.). When a user is working with the canvas, the canvas occupies a large share of the screen and thus dominates the interaction with the user.
The OpenSocial platform
The Open Social platform does not really require the applications to be hosted (they can be purely client side applications using HTML, XML and Javascript). The application presents itself as a gadget and can get information about the network graphs fed into it at runtime. When I refer to a client side application I shall be referring to the gadgets with type=html whereas when I refer to an application as a server side application, I am referring to those applications which are hosted with type=url.
Now for some of the important differences.
1. Application Structure
OpenSocial applications can be both client side and server side. Most of the specification and almost all the examples are those of client side applications. These typically require a high competence in HTML, XML and especially in Javascript. The applications can also be server side but this does not seem to be a predominant mechanism of application serving as yet.
Facebook applications are all hosted on a web site. These typically require a reasonable amount of server side development using a variety of languages. PHP and Java client libraries are provided and supported by Facebook. However client libraries in other languages are also available.
2. Application predominance
In facebook one application is predominant at a time since the canvas it is provided occupies a majority of the rendered screen space. It is not yet clear how most OpenSocial applications will get presented, though it is quite likely that many of these will coexist on one screen with different independent spaces assigned to them
3. Control
In facebook, the facebook site itself acts as a reverse proxy between the browser and the application with some substantial mod_rewrite functionality. It thus intercepts the traffic and actually changes the data stream on the fly (eg. by changing all the javascript variable names). The facebook site is always firmly in control.
In case of OpenSocial, the application is provided a space for its gadget to be hosted, and after that the application is firmly in control ie. the browser communicates directly with the application.
4. Development Skills
Facebook application development skill requirements are likely to be more similar to those required by the conventional server side application development. However the developers will need to learn the facebook platform apis and technologies (eg. rest apis, FBML, FQL etc.).
With OpenSocial if the application is a server side application, the development skill sets are likely to be similar to those of typical server side application development with a lesser requirement to learn newer APIs. However if the application is a client side application and you don’t have serious javascript capabilities, be ready to invest in that quite a bit if you want to create a slick app.
In a scenario where one is using a client side Open Social app, it just seems like the entire controller is getting moved over to the client, and it takes some substantial skills and effort to work through all the interactions in Javascript. I like HTML+Javascript, but dont particularly look forward to writing any more than what is necessary. I generally found that it was relatively faster to work with creating Facebook apps especially in scenarios where a reasonable amount of server side processing was required (FBML is quite helpful).
5. Application or applet
While one can potentially build both applications or applets with both the platforms, seems like the focus of Facebook is to build applications while that of Open Social is to build applets (small focused functionality) which primarily seems to stem from the fact that OpenSocial borrows heavily from the Google Gadget infrastructure which itself was not focused on heavy duty application development.
6. Usage of IFRAMES
OpenSocial is likely to depend a lot more on the usage of IFRAMEs. While older facebook applications used IFRAMEs, many contemporary applications do not. Combined with the fact that due to Facebook acting as a reverse proxy, which ensures that the data stream is coming from a single domain, some of the difficulties associated with IFRAMEs especially for passing information across domains and usage of SSL with IE (where I’ve in the past faced some difficulties) can be avoided easily in Facebook.
7. Security
I am going to go on a limb here and make a conjecture here - Given facebook’s reverse proxy structure and given the fact that its platform had some reasonable time to develop (unlike OpenSocial which just seems like a lets make Google Gadgets into a platform API as fast as we can approach), its “probably” going to be tougher to build more secure applications under OpenSocial
8. Platform data is being pulled or pushed ?
In case of Server side OpenSocial applications, the relationship graph and user preferences are pushed into the application as a part of the URL itself (reminds me a little bit about dependency injections - except that it is being done for data). Additionally the application can communicate with OpenSocial platform through REST based APIs but these specifications are currently still in progress. In case of client side applications, this data is pulled from the OpenSocial platform and mashed up with the application data on the client side.
Facebook also supports the pull and push models but a little differently. While it has a well defined REST interface along with the corresponding language bindings into PHP and java, it allows the application to pull data from facebook as well as push it to facebook (eg. to write to feeds). However given the reverse proxy structure, in a way Facebook is really pulling the entire application content from the application before it mashes it up on its site (eg. processing FBML tags or changing javascript variable names) before sending it to the browser.
9. Standards compliance
Clearly OpenSocial could be “considered” to be more standards compliant. However that is a rather mixed blessing - All the proprietary facebook additions eg. FBML tags actually help reduce a fair amount of development effort with no equivalent capability in OpenSocial yet. There still are many things that Facebook platform supports which are as yet unaddressed by OpenSocial, so I am not so sure if the issue is so important yet. But as OpenSocial starts offering more capabilities in future versions this could start becoming an issue.
Summary
Clearly there exist quite a few dissimilarities between OpenSocial and Facebook platforms. These differences are sufficiently large enough to tempt me to call them apples and oranges (though their end goal is to feed me). It would be wise to avoid the question “which one is better ?” However I can indeed state that as a developer having spent a large time on building server side enterprise applications, facebook just seems to be a lot more enjoyable to work with along with it likely to be more stable and more secure. But remember YMMW (some people like apples more and others oranges).
This post continues from OpenID or OpenAvataar ? UserID or AvataarID ?, and Implications of OpenID on software design and specifically looks at how the OpenID specification could be used within corporate intranets and extranets.
Why would a corporate even want to implement OpenID
The problem OpenID is attempting to solve is widely prevalent within corporates as well. There are multiple applications, databases, web sites etc. which seem to want to create their own userid / password combinations. There is an enormous amount of activity and effort that a corporate has to invest in identity management. Additionally there is today a compelling need to for a user to transparently navigate across a wide variety of corporate applications especially in situation where each application performs its identity management tasks independently. This is precisely one reason why identity management, and Single Sign On are terms which are in many cases far more important to a software designer within a corporate context than on the public internet.
What is different about corporate environments
For starters, there is a much stronger need within corporate environments to be able to associate a person’s identity with the authentication mechanism (eg. OpenID). I argued earlier that OpenID should reflect avataars and not necessarily a specific person’s identity especially within the public internet’s context. However many social interactions on the internet are relatively casual in nature and in most cases are likely to be sufficiently non-risky at least when looked at strictly from a commercial transaction perspective. The internet is a very democratic environment where most people are treated as fairly equal to each other. Within a corporate environment however each person has varying roles and along with that comes a varying set of responsibilities. It is fairly unlikely that corporate environments would easily allow any arbitrary OpenIDs (such as one created by a employee from one of a plethora of Internet based OpenID providers or even by creating a self hosted provider on his desktop himself). Corporates will be compelled to define ACLs around various corporate resources and these will need to be based on user identities and not their avataars.
How could a corporate implement OpenID ?
First there would need to be sufficient conviction that this indeed helps solve the problem more effectively than many other Identity Management solutions out there (Some of the competing strategies are based on LDAP and SAML). Assuming that one reaches that conclusion, the way forward would be to either identify specific public OpenID providers or more likely create an internal OpenID provider (which may in turn be a layer on top of the Directory Services). The URLs as registered / provided from this internal providers would serve as a mechanism for the user identity presentment and verification.
Would there be a conviction that OpenID would be able to provide better identity verification solutions than the other solutions out there ? I suspect not always. However it is more likely in scenarios such as follows :
(a) Its a highly decentralised and large corporate with independent identity management functions being carried out by a variety of sub units.
(b) There is a necessity to establish broader extranets and expose the corporate application to other partners or consume applications and services provided by various partners.
Even in both the above situation there are other identity management solutions that do exist. However I do believe that OpenID is better placed at being able to find its place in these situations given the relative simplicity of implementing it and more importantly the notion of standardisation that it brings with it. Moreover in a heterogenous world especially with all the various partner organisations and the identities that these spawn (which could be maintained in fairly diverse ways using different technology platforms) also starting to play a role, there will be a necessity for identity management, presentment and verification solutions to start talking one lingua franca and OpenID just might be it. There are other claims to be already having the common language (eg. SAML, LDAP), but I suspect the advantage OpenID brings in terms of a standard, widely used specification and especially in terms of it riding primarily on HTTP will help it hold its own in many situations. It is imjportant to note here that SAML perhaps provides a much more structured mechanism of data exchange and providing more sophisticated assertions about the user identity and it may be so that it is more appropriate in a given context. However I believe OpenID is likely to be used more often than SAML in most less intensive cases primarily because of its simplicity and given the presumption that OpenID is far far more likely to be successful in the internet than SAML.
However OpenID only solves a part of the problem - ie. identity of the users. Within extranets, sometimes its important to establish the identity of the partner organisations as well. OpenID is unlike to be able to solve the same by itself. However there are other initiatives such as inames which are at least attempting to solve that piece of the puzzle though it would be important in such cases that the individual inames and OpenIDs be seamlessly integrated.
In my earlier post OpenID or OpenAvataar ? UserID or AvataarID ? , I referred to the fact that a user may have multiple OpenIDs (my hypothesis being that these will reflect his various avataars). The question I attempt to answer here is how will usage of OpenID impact the design of the software itself.
Case of a site with OpenID integration
Here’s where things get interesting. One of the sites I went to dzone which is supposed to be for developers. It supports OpenIDs, but when I try to go to the registration page, here’s what I get.

Notice that the site seems to be supporting an OpenID login (bottom right) but yet goes on to add the following : “You will need to set your password using the one-time link you received in your email before you can login.”. I could not find any way of using my openID without the site creating a new user id and a password for me that it would send me to my email address. (And this is a rather geeky set of sites which seems to implement a single user id across JavaLobby, EclipseZone, dzone and JavaBlackBelt.). Clearly this was not how I believe OpenIDs were intended to be used (remember they are supposed to reduce userids and passwords) since the site expects me to create one more userid and one more password.
I shall assume that these sites are in the middle of a incremental transformation towards an OpenID oriented site and hopefully at a future date, I can simply register myself using my OpenID without creating any new userid or password.
Design considerations when using OpenID
I submit the following as requirements for any OpenID based account registration
- My OpenID should be my userID / accountID (i.e. I am my OpenID)
- I should not be required to provide any new userid / password
- I may be required to provide additional information required by the site which is not published within my OpenID
But wait a minute we just went past the hypothesis that multiple OpenIDs could map to one Identity (UserID?). If that has to hold true, I need a new user id to be created so that I could map multiple OpenIDs onto it. But that seems to only exacerbate the problem that OpenID originally tried to solve. ie. the runaway number of userids that I seem to be having. Clearly something does not line up well here.
The one reasonable way I can imagine this working out fine is if the site itself focuses on the Avataar / Persona / OpenID and not necessarily the user’s unique Identity. ie. The site just keeps track of Avataars and does not attempt to link it into one single user id, and does not create a password for the same. Now me as an independent professional in my individual capacity and myself as the agent of an organisation could log in into the site independently as different avataars, and the site could treat each of my avataars as simply equivalent to what would’ve otherwise been two different userids. Thus the site no longer needs to keep track of my userid or my unique identity. It simply keeps track of Avataars or Personas, and in general does not focus on specific person’s identity.
However there are some sites which require user identity specific information (e.g. Online Drivers License Renewal assuming thats allowed in your region). Clearly in such situations, additional attributes would need to get attached to the avataar which reflect the specific user identity (actually more likely - the OpenID would need to get attached to the specific user identity). Whether one should require a unique constraint around such additional attributes (eg. two avataars cannot have the same drivers license number) is probably an site / application specific decision.
It is also quite likely that I might want to change the OpenID I use for a particular avataar. So there probably needs to be an internal unique identifier for the avataar, with an ability to change the OpenID that is used to login as that avataar (similar to the ability to change the primary email address). This actually is something which the OpenID spec does not address, thus transferring the onus of maintenance of such a mapping between an OpenID and an application / site specific avataar id (which probably just would end up being an internally generated number). As an aside this is something inames does tackle explicitly
This means all global i-names have a corresponding global i-number that represents a permanent identity that will never be reassigned even if a global i-name expires or is sold.
Do I need a password field / column ?
If you are supporting OpenID users only then you no longer need it. But if you are supporting both site specific userIDs and OpenIDs you will still need to conduct authentication for the site specific userIDs. If you are building in support for OpenID in an existing application, you will probably keep the encrypted password or the password hash in the password column for the site specific user ids.
If you are building a new application however, and you still want to support users who do not have an OpenID, consider building your own OpenID provider. Thus generate an OpenID for such users only when required. Have the User Account Maintenance capabilities simply depend upon an OpenID provider (one of which could be your own). Should you want to get started on using some open source OpenID providers here’s a list of OpenID Open Source Libraries .
Summary
- Design for new user registrations using only their OpenIDs ie. no new externally known userid or password
- If migrating towards a OpenID based infrastructure, you will need both non OpenID and OpenID users to coexist.
- Map the OpenID onto an internally generated and externally invisible id.
- If you want to allow users to link up their multiple OpenIDs, build for associating each such OpenID with the same internal Id. In this case users can freely add / remove other OpenIDs, subject to the constraint that at least one OpenID always remains associated with the account.
- If you would like to deal only with the user avataars and offer separate view of your site to each of his avataars, the ability to link multiple OpenIDs together may not be required. However do allow the user to change his OpenID (since he may find a good reason to want to change his OpenID provider in the future).
- If you are interested in supporting only one id per person consider using a different externally known identifier that uniquely identifies the person (could be the social security number or driving license number or something else). That should be the internal handle to the user which is enforced as a unique identifier (you can still choose to have another internally generated id). You can now associate one or more OpenIDs with that user and allow any one of them to be used as the authentication mechanism.
- If you are building a new application ground up, consider designing your application to work with OpenIDs alone. To cater to users not having OpenIDs, build a separate small application to allow them to create and maintain their OpenIDs


