The Java Tutorial gives the standard definition of the protected access modifier:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

But what does this mean in practice? I see a lot of confusion that can be best cleared up by showing some code. Below are five classes. The first three are in one package, the second two in another:

package com.stevideter.java;
 
public class X {
    protected void doSomething() {
        System.out.println("did something");
    }
}
package com.stevideter.java;
 
public class Y extends X {
 
    protected void doSomethingElse() {
        // inherited from X
        super.doSomething();
        X x = new X();
        // visible b/c of same package
        x.doSomething();
    }
}
package com.stevideter.java;
 
public class AccessTest {
    public static void main(String[] args) {
        X x = new X();
        // visible - same package
        x.doSomething();
        Y y = new Y();
        // visible - inherited in same package
        y.doSomething();
    }
 
}
package com.stevideter.java.examples;
 
import com.stevideter.java.X;
import com.stevideter.java.Y;
 
class Z extends X {
    protected void myDoSomething() {
        // can call as part of implementation
        super.doSomething();
        X x = new X();
        x.doSomething(); // compile time error; declared in different package
    }
}
 
public class ExternalAccessTest {
 
    public static void main(String[] args) {
        X x = new X();
        x.doSomething(); // compile-time error, not visible
        Y y = new Y();
        y.doSomething(); // compile-time error, not visible
        Z z = new Z();
        z.doSomething(); // compile-time error, not visible
        z.myDoSomething();
    }
 
}

Here we see that while we operate in the same package, we can always access class X’s protected method doSomething(). Subclass Y can access it via inheritance, and AccessTest can see doSomething() for X, because it’s in the same package, and Y because Y inherited it from X and is in the same package.

In the second package, we see that access to X’s protected method is far more restricted. Subclass Z can use doSomething() as part of its own implementation. But it cannot access it via an instance of X.

ExternalAccessTest, on the other hand, simply cannot see doSomething(). This is true for X, because X and ExternalAccessTest are in different packages. But perhaps it’s surprising that it cannot see it in Z, which is in the same package as ExternalAccessTest. The reason is that although Z inherits doSomething from its parent class X, because doSomething() is in fact declared in a different package, that method is not visible in the new package.

It’s this final case that seems to cause the most confusion. Z does inherit the protected method doSomething(). But that inheritance is restricted by that protected access modifier. The inheritance doesn’t “override” the original declaration.

I’ve seen several programmers struggle with a similar question. They create a collection of some sort, and add items to it in a loop. When they finish the loop and try to use the collection (or list, or array, or set, or map) it looks like every single object in the collection is the same one — the last one added to the array. Usually they’ve written code that looks something like this C# example:

using System;
using System.Collections.Generic;
 
namespace Stevideter.ArrayTest
{
    public class Program
    {
        static void Main(string[] args)
        {
 
            List<Person> people = new List<Person>();
            Person person = new Person();
            for (int i = 0; i < 3; i++)
            {
                person.Name = String.Format("Person {0}", i);
                person.Age = i * i;
                people.Add(person);
            }
 
            foreach (Person person1 in people)
            {
                Console.Out.WriteLine(person1);
            }
        }
    }
 
    class Person
    {
        private String name;
        public String Name
        {
            get { return name; }
            set { name = value; }
        }
 
        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
 
        public override string ToString()
        {
            return String.Format("{0} is {1}",name,age);
        }
    }
}

What happened? Why is the output:

Person 2 is 4
Person 2 is 4
Person 2 is 4

The answer is in the mystery that is parameter passing by value.

In both Java and C#, parameters are passed by value. But what this means for objects is not what you may intuitively expect. When you pass an object reference to a parameter, the value that is passed is, in fact, a copy of the reference, not a copy of the object that is referenced. Both the original reference and the value copy point to the same object. That is why you can update the members of an object in a method that you pass it to - you have a copy of the address where that object lives on the heap.

In the code above, only one Person is created. Each trip through the loop, the members of
person are updated. When people.Add(person) is called, the reference to the object created by new Person() is copied and added to the List people.

When you change the object’s values the next time through, every reference to that object sees the changes, because they all still point to the same instance on the heap. This is why at the end, every item in the array has the most recent updates. The code, as usual, is doing exactly what you told it to do.

Instead, you need to create a new object for each object you want in the array, and add that new reference to the array. This time, let’s see it in Java:

package com.stevideter.java;
 
import java.util.ArrayList;
import java.util.List;
 
public class ArrayTest {
 
    public static void main(String[] args) {
 
        List<Person> people = new ArrayList<Person>();
        for (int i = 0; i < 3; i++) {
            Person person = new Person();
            person.setName(String.format("Person %d", i));
            person.setAge(i*i);
            people.add(person);
        }
 
        for (Person person : people) {
            System.out.println(person.toString());
        }
    }
}
 
class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return String.format("%s is %d", name, age);
    }
}

This time we get the results we probably expected:

Person 0 is 0
Person 1 is 1
Person 2 is 4

At this point, you might be confused by the issue of scope, and feel you must declare and instantiate the object outside of the loop, afraid of losing the object when the loop ends.

What is actually lost when we leave the for loop is access to the reference person.
But the references to the heap location for the object created by each call to new Person() still exist. So the objects are still in the heap, and can still be used via the array/collection to which they were added.

I know I still get caught now and again by the implications of pass by value in Java and C#. When is the last time it surprised you?

This article on Making Small Commits lead me to think about when to commit and when to branch a code base.

Branching is the black art of version control, and anyone who has tried it at least once has probably had the nightmare that arises from having to merge code back in.

It’s an art worth learning, however. Sometimes you’re working on a feature, or a refactor, that’s significant enough that you can’t risk partial checkins.

Now, for context, I’m a big believer in frequent checkins. Beyond the advice in the linked article, I tend to check in almost any change. Add a method? Check it in. Add a single unit test? Check it in. Version Control is my brain and my undo. I’d rather revert a version or 10, but be confident, than realize I need to go back about halfway through my current rewrite.

Given I like, and in fact need, to check in often, I feel I probably need to use branching more often, as well. An recent example was work we started for a client. Right after integrating the first elements of the new features, the client changed the current request. Entirely. However we were stuck deep enough in a combination of new elements not yet finished and concurrent refactoring that it became easier to comment out large sections of code than refactor. If we’d just branched the new feature set, and continued maintenance on the trunk version, we would have saved ourselves frustration - and the risk that comes from half-finished features that probably won’t ever make it to the top of the backlog again!

What is your philosophy on branching your code base?

This post on the JavaRanch Big Moose Saloon led me to fire up Eclipse and write some test code. The question is basically how can you use the ability to map a parent bean as part of a bean definition in Spring.

Let’s look at three classes and see how they can be mapped using Spring.

public abstract class SuperBean {
	private int id;
	private String name;
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
}
 
public class SubBean extends SuperBean {
 
	private String newProperty;
 
	public String getNewProperty() {
		return newProperty;
	}
 
	public void setNewProperty(String newProperty) {
		this.newProperty = newProperty;
	}
 
}
 
public class DifferentBean {
	private int id;
	private String name;
	private String myProperty;
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getMyProperty() {
		return myProperty;
	}
 
	public void setMyProperty(String myProperty) {
		this.myProperty = myProperty;
	}
 
}

now let’s map them in Spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 
    <bean id="superBean" abstract="true"
        class="com.stevideter.spring.SuperBean">
        <property name="id" value="1" />
        <property name="name" value="superBean" />
    </bean>
 
    <bean id="subBean" class="com.stevideter.spring.SubBean"
        parent="superBean">
        <property name="id" value="2" />
        <property name="newProperty" value="subBean" />
    </bean>
 
    <bean id="differentBean" class="com.stevideter.spring.DifferentBean"
        parent="superBean">
        <property name="id" value="3" />
        <property name="myProperty" value="differentBean" />
    </bean>
</beans>

And now let’s write a simple app to show what happens with these mappings:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestClass {
 
    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] {"applicationContext.xml"});
 
        SubBean subBean = (SubBean)context.getBean("subBean");
        System.out.printf("ID: %d, Name: %s, Property: %s\n",
                                subBean.getId(), subBean.getName(), subBean.getNewProperty());
 
        DifferentBean differentBean = (DifferentBean)context.getBean("differentBean");
        System.out.printf("ID: %d, Name: %s, Property: %s\n",
                                differentBean.getId(), differentBean.getName(),
                                differentBean.getMyProperty());
    }
}

If we run this class, we get the following results:

ID: 2, Name: superBean, Property: subBean
ID: 3, Name: superBean, Property: differentBean

What we learn from this is that you can use the parent attribute to map to a parent bean definition that your bean class doesn’t inherit from. What’s necessary is that the classes are compatible, which means that the child class has all the properties that are defined in the parent class. In fact, the documentation notes you don’t have to declare a class on the parent definition at all.

I find it more useful to think of the parent definition as a template, to avoid the trap of thinking it is an object-oriented style of inheritance. Another way to think of it is as a parent interface for the child bean; you must implement these properties in order to use this definition.

I signed up for Twitter way back in the day when picking a short name (smd) was important because most people I knew were still using it for the intended SMS purpose. Like so many other new services, I more or less forgot about it, occasionally checking back when someone mentioned it.

In the past week, I caught Tweet fever (I blame avflox’s livejournal post) and have seriously been experimenting with Twitter again. Naturally the web interface wasn’t interactive enough for me, so I started experimenting with clients. Many people have been recommending twhirl so I gave it a try.1

Overall, twhirl is quite nice, although I find myself constantly accidentally exiting by clicking the ‘x’ on my client. Since twhirl appears in my system tray, I expect closing the window to minimize it to the system tray, not completely exit the program.

That aside, my biggest annoyance was that when I clicked a URL in a tweet, it was opening up in IE instead of Firefox, my default browser. I found reference on the twhirl site to how to fix this issue in Vista, but no posts or comments about this being an issue in XP.

I had Firefox check, and it believed it was the default browser. IE knows it’s not the default browser. When I click URLs in Outlook, they open in Firefox.

I went to Control Panel > Add or Remove Programs > Set Program Access and Defaults > Custom and saw that while “Use my current Web Browser” was select as the default, Firefox didn’t appear on the list. Just IE and Safari. As an experiment, I chose Safari, went to twhirl, clicked a URL, and sure enough, it opened in Safari.

So I reinstalled Firefox, went back to the control panel, and saw that Firefox was now an option. I selected it, clicked ok, and clicked another URL in twhirl. Finally, success.

[1] must. resist. obvious. rhyme.

We had a very fruitful. frank conversation with the business analyst for the main project I’ve been working on for the last two years. We discovered a lot of the pain points for users and now know there’s concrete things we can do in the next sprint or two to really help them out.

But what really made me smile was her comment, while describing the current user workflow, that a feature I spent a lot of cycles on was really appreciated. “The users love that, it really saves them a lot of time.”

It was frustrating to implement, with lots of tiny gotchas, while not being terribly technically interesting. I must confess, I didn’t particularly enjoy coding it. So it was a great reminder that even the drudge work can make a difference.

I quite like the Microsoft Membership Framework for handling membership roles, authentication, and security resources in ASP.NET applications. It’s easy to create the initial user login and management framework for a new application, then swap in a more sophisticated Provider as needed.

For my current project, we have a new requirement to allow logins against multiple user stores. The existing application validates against an Active Directory store. But for a subset of users, there is a need to check if they are in a SQL Server database and allow them to login while they wait for their Active Directory setup to complete. This SQL Server also contains a secondary set of roles that will be relevant for any user that is in the SQL Server user store, regardless of whether they were validated via AD or the SQL Server.

The first step I took was to figure out the easiest way to have two separate providers to validate the user. You can configure as many membership providers as you want in the web.config for your application, but you choose a default provider as part of the setup. If you use the standard Login control, it will only check against that default provider.

In order to change that behavior, I overrode the Login.Authenticate event for my Login control. The method looks a little like this:

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool foundUser = false;
        List<string> roles = new List<string>();
        roles.Add("GeneralUser");
        // this will call the default MembershipProvider
        if (Membership.Provider.ValidateUser(LoginBox.UserName, LoginBox.Password))
        {
            foundUser = true;
            // do any additional lookups for this type of user (Default MembershipProvider) here
        } // otherwise, explicitly call secondary provider
        else if (
            Membership.Providers["SecondarySqlMembershipProvider"].ValidateUser(LoginBox.UserName,
                                                                                LoginBox.Password))
        {
            foundUser = true;
            roles.Add("SecondaryUser");
            // do any additional lookups relevant to this type of user
        }
        if (foundUser)
        {
            Session["UserId"] = LoginBox.UserName;
            Session["Groups"] = roles;
        }
        e.Authenticated = foundUser;
    }

I didn’t need to modify the Authentication Ticket or cookie, so I could rely on the Membership Framework to handle the rest. If I need to add additional information, I can do it in the commented spots to correctly handle the type of user I care about.

I frequently use the CocktailDB web site to find and compare cocktail recipes.

Being a lazy programmer who uses Firefox, I got fed up with having to go to the main search page to start a new search, so I finally decided to experiment with making an OpenSearch plugin so I could start a search right from the Search Engine section of my Toolbar.

I found the information on the Mozilla Developer site to be sufficient to get me going. The only real issue I hit was figuring out all the right parameters to send in post to the search url. Happily, LiveHTTPHeaders solved this with one request. I turned on LiveHTTPHeaders from Tools, made a request from the normal search page, and voilà, all the parameters were captured for me to examine and add as needed to my OpenSearch xml document.

Within a half-hour, I had two different OpenSearch plugins, one to search by recipe name, and one by an ingredient. I used URI kitchen to get the correct string to format the favicon.ico that CocktailDB uses on their site, created an html page with links in the headers to enable autodiscovery, and I was good to go.

You can try the plugins for yourself by visiting my autodiscovery page and adding one or both plugins. Enjoy, and maybe you’ll be inspired to create a search engine plugin for one of your frequently used sites. Or to mix yourself a nice drink.

Cheers!

A problem I just faced: I was trying to use Visual Studio 2005 on my Windows XP box to connect to a Team Foundation Server (TFS) via VPN to check out some source code. I would attempt to connect to the server, and would then receive the error message that USERA did not have permission to access the server.  The problem was, I didn’t want to connect to the server as USERA, but rather as USERB. It would never give me a login prompt, however, just repeat the message that I could not connect as USERA.

I was VPN’ed into the system via Cisco, and thus hadn’t yet given any Windows network credentials, so I was puzzled from where it was getting the opinion I wanted to be USERA.

After trying to delete the server multiple times and add it back in, it finally occurred to me that I had connected to that server via Network Places. I opened the Network Places window, but the server didn’t show up there.

Finally I started hunting through control panels. I hit upon User Accounts, opened that, and clicked the Advanced tab. I clicked the Manage Passwords button, and there under Stored User Names and Passwords, wouldn’t you know it, an entry for the server in question. I selected it, clicked Remove, and Closed out of the User Accounts Control Panel.

I tried to connect to TFS through File > Open from Source Control, selected my server, and got the login box I expected instead of an error message. Progress!

Moral of the story: be very careful when you select the option for Windows to remember your login credentials. It may have unintended consequences. And if you let your OS  (or any application/system) cache your login information, be sure you know where to go to change it in case you need to.

A common feature I’ve found necessary for web applications is role-based security at the field level. For example, I may have a form that allows editing a user’s information. The requirements may include the rule that only certain types (roles) may edit certain fields.

This can be accomplished in myriad ways. You can create a different form per role, and direct the user to the appropriate form. Or you can put specific logic around each relevant field to show, enable, or hide each field.

Both these routes can lead to a lot of extra coding, and even more maintenance. I’d like to be able to tell each affected field to display itself correctly based on the user’s role.

The Microsoft.NET Framework 2.0 introduced the Membership and Roles framework and the Microsoft Provider Model, which gives us an API-based way to interface with users and roles. If you use a RoleManager (either one of the defaults provided or your own custom implementation), the following code gives an example of how you can extend the existing WebControls to render themselves based on a current user’s roles.

using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.ComponentModel;
namespace RoleAwareServerControls
{
    ///
    /// Role Aware Text Box. Will only render as Enabled if user is
    /// in the in the RoleName.
    ///
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:RoleAwareTextBox runat=server RoleName=user></{0}:RoleAwareTextBox>")]
    public class RoleAwareTextBox : System.Web.UI.WebControls.TextBox
    {
        private bool visibleIfUnauthorized;
        ///
        /// if user is not in role, should the field be displayed at all?
        ///
        public bool VisibleIfUnauthorized
        {
            get { return visibleIfUnauthorized; }
            set { visibleIfUnauthorized = value; }
        }
 
        private String roleName;
        ///
        /// if user is in this role, enable this field, else not
        ///
        public String RoleName
        {
            get { return roleName; }
            set { roleName = value; }
        }
 
        ///
        /// determine if TextBox should be Enabled or Visible
        ///
        ///An EventArgs
       /// that contains the event data.
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            // assume normal display if RoleName not set
            if (!String.IsNullOrEmpty(roleName))
            {
                Enabled =
                    (Page.User.Identity.IsAuthenticated && Page.User.IsInRole(roleName));
                Visible = Enabled ? true : visibleIfUnauthorized;
            }
        }
    }
}

To use the new web control, register it with your page (or for the whole application in your web.config) and add it to the page:

<%@ Page Language="C#" MasterPageFile="~/Site.master" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="_Default" Theme="Default" %>
<%@ Register TagPrefix="rasc" Namespace="RoleAwareServerControls" %>
<body>
    <form id="form1" runat="server">
        <rasc:RoleAwareTextBox runat="server" ID="textBox"
            RoleName="administrator" VisibleIfUnauthorized="true" >
            Hi, administrator</rasc:RoleAwareTextBox>
    </form>
</body>

Next Page »