Problem installing extensions in Firefox

Today I tried to install some new browser extensions into the latest Firefox 0.9.3 browser and couldn't figure out why nothing was happening. I first tried opening the XPI file directly from the Mozilla Update extensions page. I clicked on one of the extensions I wanted (Adblock, highly recommended), and clicked the "Install Now" link. Nothing happened, like it wasn't recognizing my click.

Next attempt: Download the XPI file, and try to install it that way. I saved the adblock-0.5-dev.xpi file to my disk, then went into Firefox's File / Open File... menu to open it. Nothing happened. It was like Firefox was just going to ignore the fact that I asked it to open the file.

Next attempt: Drag the XPI file from the folder into Firefox and have it open the file that way. Still, nothing happened.

I went to the Tools / Extensions menu item to see if something was stopping me from installing extensions, an error message, something. No joy.

I searched around the Internet looking for people with similar problems. I checked out the Firefox help on Firefox forum. Nothing pointed me in the right direction.

Finally, I tried hunting around in all my Tools / Options... settings to see if something there would help me out. Hmm. Tools / Options / Advanced / Software Updates / Allow web sites to install software. There it was. I had, many months ago, unchecked this box for security reasons when I first installed my browser. Even though I was installing the XPI file locally and not from a web site, that security option was stopping the extension from being installed (which is a good thing).

Summary: User error. Firefox was doing exactly what I had told it to do. While I'm suitably chagrined, it sure would have been nice if Firefox would have told me what I was doing wrong rather than ignore my attempts to install the XPI files. How about an error dialog, "Your security settings prohibit installation of browser extensions."

Next stop: A check of the bugzilla site to see if this feature is on the to-do list.

Update: Bugzilla has this problem logged as Bug 248486.

Two duplicate bug reports were filed by others similarly frustrated. It looks like someone wrote a patch for it, so maybe the fix is in the nightly builds even now. But I'll wait until Firefox 1.0 comes out to enjoy the fix.

Using JDK 5 varargs as bulk setter method

After thinking I couldn't see using the new varargs feature in JDK 5 every day, I thought of a potential use that could cut down on repetitive code: initializing a bean or value object.

As an example, say I wanted to create Person class that contains the person's first name, middle name, last name, and a nickname. I want all values to default to an empty string if not supplied by the caller.

For a standard Java bean, I could create a class with all the "name" instance variables initialized to the empty string, then write setters for the values. That way, Person bean instances would have the values set by callers, but contain empty strings for any values unset. For convenience, I'd probably include a bulk setter method that would take all four strings. Something like:
setAllNames(String last, String first, String middle, String nick) {
lastName = last;
firstName = first;
middleName = middle;
nickName = nick;
}
But maybe the caller would want to just set the first name and last name. Of course, they could call the method passing in empty parameters:
setAllNames("McQueeney", "Tom", "", "");
but for convenience -- especially if there were more the two unneeded parameters, I'd probably want to provide the method:
setLastFirst(String last, String first) {
lastName = last;
firstName = first;
}
And now I can see where having a method that would take a variable number of arguments could help.

As a test, I wrote the following sample Person class. Instead of providing all the setters and getters and creating a bulk setter, as mentioned above, I put all property-setting in the constructor for two reasons: first, to keep the code short, and second, to show that a varargs constructor becomes the default constructor. This seems like a neat little feature. (While in the back of my mind I'm thinking, "How are programmers going to abuse this neat feature?")

Here's my Person class, coded using JDK 5.
public class Person {
private String lastName;
private String firstName;
private String middleName;
private String nickName;
public Person(String... params) {
lastName = firstName = middleName = nickName = "";
if (params.length > 0) lastName = params[0];
if (params.length > 1) firstName = params[1];
if (params.length > 2) middleName = params[2];
if (params.length > 3) nickName = params[3];
if (params.length > 4) {
throw new IllegalArgumentException(
"Constructor called with too many arguments"
);
}
}
public String toString() {
return "last: '" + lastName + "', first: '" + firstName +
"', middle: '" + middleName + "', nick: '" + nickName + "'";
}
public static void main(String[] args) {
System.out.println(
"No args: " +
new Person()
);
System.out.println(
"1 arg: " +
new Person("McQueeney")
);
System.out.println(
"2 arg: " +
new Person("McQueeney", "Tom")
);
System.out.println(
"3 arg: " +
new Person("McQueeney", "Tom", "X")
);
System.out.println(
"4 arg: " +
new Person("McQueeney", "Tom", "X", "Spiff")
);
System.out.println(
"5 arg: " +
new Person("McQueeney", "Tom", "X", "Spiff", "bad!")
);
}
}
(I'm not recommending the above coding style as a best-practice!) Here's the output:
> java -cp . com.mcqueeney.tiger.Person
No args: last: '', first: '', middle: '', nick: ''
1 arg: last: 'McQueeney', first: '', middle: '', nick: ''
2 arg: last: 'McQueeney', first: 'Tom', middle: '', nick: ''
3 arg: last: 'McQueeney', first: 'Tom', middle: 'X', nick: ''
4 arg: last: 'McQueeney', first: 'Tom', middle: 'X', nick: 'Spiff'
Exception in thread "main" java.lang.IllegalArgumentException:
Constructor called with too many arguments
at com.mcqueeney.tiger.Person.(Person.java:19)
at com.mcqueeney.tiger.Person.main(Person.java:51)
The benefit of varargs now is I can provide a bulk property setter with only one method, and allow the caller to pick how many of the properties to set.

Of course, bulk setters like this suffer from the same problems as other bulk setters:
  • You can't name the parameters, so you have to read the javadocs to figure out what order to pass everything.
  • You still have to provide the missing values for properties in the "middle" of the varargs set that you really don't want to set.
(By the way, I think the Groovy language allows you to specify the parameter names when you call a method.)

I can see bulk setters using varargs reducing some code. For instance, the java.util.GregorianCalendar has constructors that takes initial values for the date and time:
public GregorianCalendar(int year, int month, int dayOfMonth);
public GregorianCalendar(int year, int month, int dayOfMonth,
int hourOfDay, int minute);
public GregorianCalendar(int year, int month, int dayOfMonth,
int hourOfDay, int minute, int second);
which seem like they could be implemented with one Integer varargs constructor, using the new auto-unboxing feature in JDK 5 to easily set the integer properties. (Out of curiosity, I checked the source code for JDK beta 3 Build 60, and, no, they didn't retrofit GregorianCalendar this way.)

When searching around the Internet for code samples using varargs, one of the more-complete explanations was this Chapter 5 excerpt from Java 1.5 Tiger: A Developer's Notebook, by Brett McLaughlin and David Flanagan.

New features in JDK 5

Here is a summary of the new language features coming this fall in JDK 5, taken mostly from a talk given Wednesday by Joshua Bloch and Neal Gafter at the Denver Java Users Group.

The seven language changes in Java 1.5:
  • Generics
  • For-each loop
  • Autoboxing/unboxing
  • Enums
  • Varargs
  • Static imports
  • Annotations (metadata)
There are additional features and new libraries coming in 1.5 (easier multi-threading, disconnected JDBC rowsets, JMX added to the core language, dynamically generated stubs to eliminate almost all need for RMIC, and more!), but the above are actual syntax changes. Josh said Sun's primary goal of the language changes was to make our lives as programmers easier -- less typing, clearer programs, easier to avoid mistakes.

Here's a summary of the features I'm likely to use right away in everyday programming. You can read more about new features from Josh and Neal's presentation slides. Read on if you want more of the explanation you would have heard had you been able to attend their presentation in Denver.

Generics, autoboxing, for-each

Josh showed a simple program that demonstrates these new features:
import java.util.Map;
import java.util.TreeMap;
public class Frequency {
public static void main(String[] args) {
Map<String, Integer> m = new TreeMap<String, Integer>();
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
}
System.out.println(m);
}
}
Running the code would look something like this:
$ java Frequency if it is to be it is up to me
{be=1, if=1, is=2, it=2, me=1, to=2, up=1}
The first odd-looking line,
Map<String, Integer> m = new TreeMap<String, Integer>();
says to create a TreeMap that stores only Integers using only Strings as the map's key. When you create a map by defining the actual types in the declaration, the compiler won't let you use a non-string as the map's key, and won't let you store something that isn't assignable as an Integer to the map's value. The benefit?
  • Compile-time type safety
  • No ugly casts
How's that for making coding easier! Josh Bloch called it "stronger typing with less typing."

Now, take a look at the for loop:
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
}
This code demonstrates the new for-each syntax, autoboxing and autounboxing.

The loop reads almost as written: "For each string word in the args array..." The locally scoped variable word will be assigned each element in the args array on each pass through the loop. No need to index the array. The for-each loop syntax works with all the Collections types, too, which Josh dubbed "syntactic polymorphism." No more writing iterators when all you want to do is loop through a collection from beginning to end.

If you need to access the iterator in the loop, you can still write the loop the old way. Like if you want to iterate through the elements in an array list:
for (Iterator i = myList.iterator(); i.hasNext(); ) {
// ...
}
Josh says there was some desire, for clarity, to use a new foreach keyword in the new loop syntax, and to use the word in instead of the colon. But adding keywords would guarantee existing code would break. (For instance, since you can't use a keyword as a variable name, not only would System.in be illegal, but how many in variables are in your code?)

Java 1.5 is completely backwards compatible . Rather than break backwards compatibility, Sun opted to go for the slightly less-readable syntax by using non-keywords like a colon and ellipse (for varargs, below).

Not only is the for-loop syntax new in the above code, look at the lines inside:
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
The first line shows the power of generics. Since the Java Collections classes have been "generified" in JDK 1.5, and the code creates the map m by defining the key and value types, there is no need to cast m.get(word) to an Integer before assigning it to the Integer variable.

The second line shows autoboxing/unboxing in action.

Autoboxing is a fancy way of saying, "If you use a primitive type where only the object wrapper type is legal, automatically insert a constructor for the object wrapper type." That is, if you use an int where only an Integer object legal, the compiler will automatically insert new Integer([primitive value]) for you. Autounboxing is the opposite: If you use a primitive object wrapper type, such as Integer, where only the primitive type, like int, is legal, the compiler will automatically insert code to get the object's primitive value.

Note the definition: The compiler does the work. It will actually insert the bytecode into the .class file as if you wrote it. The objects still get created and the methods like Integer.intValue() are still called. The "auto" nature of boxing/unboxing just means you don't have to go through the chore of writing all that "obvious" code.

Speaking of clutter, here is the "old" way writing the above code.
Integer freq = (Integer) m.get(word);
m.put(
word,
freq == null ? new Integer(1) : new Integer(freq.intValue() + 1)
);
Hmm, I bet you're beginning to like this generics and autoboxing stuff.

Varargs

Although I think varargs will make some code clearer and easier, I don't see using them every day like I will the new for-each loop, generics and autoboxing.

Varargs will allow you to declare a method that takes a variable number of arguments. Josh and Neal's varargs example demonstrates a new varargs format method in the java.text.MessageFormat class:
public static String format(String pattern, Object ... arguments) {
// method body not shown
}
The ellipse is actually part of the Java language, not an indication I left some code out. With the above format method, you can now call it with a variable number of arguments, like:
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet " +
"{0,number,integer}.",
7,
new Date(),
"a disturbance in the Force"
);
Java does the work for you of wrapping the arguments into an object array. Less coding for you. Less clutter. And, yes, C programmers rejoice: There is a new System.out.printf in Java 5 that had been missing from Java for nine years because of the inability to pass a variable number of arguments to a method.

As you can expect, the varargs parameter must be the last one in the method's parameter list, since all remaining parameters will get packaged into that varargs parameter in the method call.

Josh's advice: Don't override a varargs method. It could get confusing. Neal called varargs "kind of a dangerous language feature" because of the potential for making code harder to understand.

One nice feature I like in varargs: Instead of passing several arguments to fill out the "Object..." parameter, you can also just pass an object array. So if you already have your method params packed into an array, you can just pass it to the varargs method just as you would to a "simulated" varargs method today.

Other new features

You can read about the other new features, enums, static imports (blechh!) and annotations in Josh and Neal's presentation slides and in this J2SE 1.5 in a Nutshell article from Sun.

The static import feature looks like a way to keep bad programmers from saddling us with bad code by giving them a cleaner option.

On the other hand, I think the metadata/annotations feature will be powerful once XDoclet-like tools are available to process the metatags. For now, though, unless I'm writing a web service using Sun's WSDP, which will be able to understand and use JDK 5 meta tags in an upcoming release, or the upcoming Apache Beehive, which will require annotations, I'll continue to use XDoclet to pre-process my Java code and generate the boilerplate artifacts.

Are you ready to download the JDK 5 beta? The more-stable Beta 2 has been out for a while. Build 60 of the Beta 3 snapshot has been out for two weeks. Neal said the first JDK 5 release candidate should be out shortly.

Java Puzzlers

Josh Bloch and Neal Gafter's presentation on JDK 5 was actually their second presentation of the evening at the Denver Java Users Group.

The duo warmed up the crowd of more than 120 by quizzing us about the "sharp corners" of Java -- the ones that can catch you if you're careless. For this presentation, they billed themselves as Click and Hack, the Typeit Brothers. That's because they parody a slightly more famous duo during their Puzzler talk.

One of their puzzler questions: What does the following program print?
public class LongDivision {
private static final long MILLIS_PER_DAY
= 24 * 60 * 60 * 1000;
private static final long MICROS_PER_DAY
= 24 * 60 * 60 * 1000 * 1000;
public static void main(String[] args) {
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
I'll give you a hint: the answer is not 1000. To find out what it does print and why, you can download their puzzler presentation from our JUG website.

You can also read their puzzler book when it comes out next year. Josh and Neal are compiling their puzzlers into a book that will show you code that behaves in a way you wouldn't expect, then tell you the "moral" the code teaches us about Java coding. I like their primary moral for coding correctly:
"If you aren't sure what a program does,
it probably doesn't do what you want."
If you'd like to send them a Java puzzler for potential inclusion in their book, email them at "javapuzzlers at gmail.com". They'll give you credit in the book if they use your puzzler.

Joshua Bloch visits Denver

Whether you call it JDK 1.5 or 5.0, I had the pleasure this week of hearing a fantastic summary of the changes coming this fall to the core Java language. Even better, I got to hear it from two of the guys responsible for the changes, Joshua Bloch and Neal Gafter. They spoke earlier this week at the Denver Java Users Group. Their presentation slides are available on our web site.

Most people probably first learned about Joshua Bloch after his 2001 best-seller, Effective Java. But Josh knows Java inside and out because he had been working on J2SE for years at Sun. Josh led the team behind the Java Collections Framework in Java 1.2 (you'll find his name on dozens of @author tags in java.util), the assertions feature in Java 1.4, and many of the features coming in 1.5. Sun honored him recently for his work on Java by naming him a "distinguished engineer." After completing changes for Java 1.5, Josh left Sun last month to become a principal engineer at Google.

Neal Gafter has developed and maintained the Java tools we use every day -- javac, javadoc, javah, javap -- and developed the JDK 5.0 language enhancements in these tools. Neal also is heading to Google as a software engineer.

Josh mentioned Wednesday that he was touched by being called the "mother" of Java by a poster on TheServerSide. The poster said if James Gosling is the "father" of Java, Josh should be considered the mother because of his nurturing of the Java language. With JDK 5, Josh and Neal have helped bring us significant enhancements to the language. Good luck at Google.

With their impressive resumes and Ph.D.'s, you'd expect these guys to have rock-star egos. But I got to have dinner with them after their presentation and was pleased to see that Josh and Neal are incredibly nice guys. When you talk to them, you can hear how much they care about Java and making it even better than it is today.

Thank you again, Josh and Neal, for your visit to Denver. I'm looking forward to your new book on Java puzzlers and Josh's JDK 5 update to his Effective Java book. I hope to see you in Colorado next year for your book tour.

Try this: Type "Josh Bloch" or "Neal Gafter" into Google and what's the first sponsored ad you see? "Google needs Java experts" or "Java jobs at Google." Computer-generated algorithm? Or Google's savvy marketing of its recent hiring of top Java talent?