2010-10-22

Java Console for Linux

From here:


Johan Dahl, 2008-09-01:


A workaround


In gnome: Select System > Settings Sun Java x.x Control Panel

In terminal: jcontrol


  1. Select the tab advanced.
  2. Expand the node "Java-console"
  3. Select show console (default is hide)

Now will the console show up the first time you run an applet. You can keep it open for debugging etc.

If you close the console window must you restart your browser to make it pop-up again.

2010-02-24

GZipOutputStream: Remember to finish() what you start!

Had an interesting experience the other day. I was creating a stream of compressed data using GZipOutputStream and ended up with lots of missing data.

It turns out that data will (may?) not be properly written to the output stream if you neglect to call finish() when you're done pumping data in. Strangely enough, neither flush() nor even close() are sufficient to accomplish this; it's either finish() or you risk having corrupt, incomplete data in your output.

2009-11-01

Eclipse button clicks in Ubuntu 9.10 (Karmic)

Since upgrading to Ubuntu 9.10, I found that some buttons in Eclipse can't be mouse clicked any more. It's usually possible to click them using the space bar, but...

Many thanks to moma for posting a solution on Launchpad!

Start eclipse with
$ cd eclipse
$ export GDK_NATIVE_WINDOWS=true
$ ./eclipse

Or use this one liner:
$ GDK_NATIVE_WINDOWS=true $HOME/eclipse/eclipse

2009-09-26

How to display a directory listing in Google App Engine

Google App Engine is really not meant to serve up a lot of static content; but sometimes you just want to!

If you put a directory full of stuff into your web archive and point your browser at it, AppEngine will tell you there's nothing there. It's possible to change that, though.

The following instructions are for the Java incarnation of AppEngine; I would imagine you can do something equivalent in the Python engine, but I don't know any details.
  • Make sure your directory and its children are marked as "static" in appengine-web.xml :
  • style-span" style="font-family: 'Times New Roman'; font-weight: normal;">Map your directory to Jetty's default servlet within web.xml :
    <static-files>
          <include path="/*.css"/>
          <include path="/favicon.ico"/>
          <include path="/code/**"/>
       </static-files>
    
  • Next, tell Jetty in web.xml to accept directory requests:
    <context-param>
          <param-name>org.mortbay.jetty.servlet.Default.dirAllowed</param-name>
          <param-value>true</param-value>
    </context-param>
    
  • Finally, define Jetty's "default" servlet in web.xml to accept directory requests:
    <servlet>
          <servlet-name>default</servlet-name>
          <servlet-class>org.mortbay.jetty.servlet.DefaultServlet</servlet-class>
          <init-param>
             <param-name>acceptRanges</param-name><param-value>true</param-value>
          </init-param>
          <init-param>
             <param-name>dirAllowed</param-name><param-value>true</param-value>
          </init-param>
          <load-on-startup>0
       </servlet>
    
       <servlet-mapping>
          <servlet-name>default</servlet-name>
          <url-pattern>/code/*</url-pattern>
       </servlet-mapping>
    

  


... and that's more or less it!

2009-09-23

My Eclipse settings

Eclipse is a great Java IDE. There are just a few things I don't like about its default configuration. Fortunately, it's highly configurable.
  • Preferences
    • General
      • Ant
        • Editor
          • Formatter
            • Tab size: 3
            • Use tab character instead of spaces: uncheck.

      • Editors
        • Displaced tab width: 3
        • Insert spaces for tabs: Check.
        • Show line numbers: Check.
        • Text Editors
          • Spelling
            • Enable spell checking: Uncheck.


    • Java
      • Code Style
        • Qualify all generated field accesses with 'this.': Check.
        • Formatter: new profile "carl"
          • Indentation
            • General settings
              • Tab policy: Spaces only
              • Indentation size: 3
              • Tab size: 3


      • Compiler
        • Errors/Warnings
          • Potential programming problems
            • Serializable class without serialVersionUID: Ignore

      • Editor
        • Folding
          • Initially fold
            • Imports: uncheck.


2009-09-03

Substring labels in Blogger

Have you ever tried giving your blog post multiple labels, one of which is a substring of the other?

Example: spring security, spring.

Once Google Blogs has latched on to the longer string, it will move heaven and earth to auto-complete the shorter one for you.

One solution is to add a comma immediately after the short string. Auto-completion won't try to overrule you then.

2009-07-30

Table height = Browser window height WITHOUT quirks mode!

In spite of all the CSS hype, I still occasionally like to use tables to lay out a page. I think there are some layout situations where a table lets you do things CSS layouts don't.

For a long time, I've been despairing about the apparent impossibility of getting a page to fill the browser screen, or a known proportion of it, independently of the user's browser window size and without using JavaScript.

It used to be that a table at 100% height would fill the screen vertically. However, this was a "feature" of the so-called "quirks mode." If you build a Web page with a "proper" DOCTYPE, you hint to the browser that you know how to build standards compliant Web pages, and in return it renders your page more or less rigidly according to the standard.

This is very thoroughly explained by Gary White on the AppTools site .

The good news is, there's a standard compliant workaround. You can use CSS to set the height of the <html> and <body> elements of the page to 100%; their parent is the screen, so they will. Then you can use CSS to set the height of your table to 100%, and it will fill your screen.

2009-07-22

import static in a JSP

I have yet to try this, but according to this post on the GlassFish forum, the way to do an "import static" in a JSP is like this:

<%@ page import="static foo.*" %>

Implementing an interface in a JSP

I've scoured the net, but apparently it's not possible to make a Java Server Page implement an interface. Not directly, anyway.

What is possible is to extend a class. The directive is:

<%@ page extends="package.class"%>


One reference for JSP page directives is: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html .

The class generated from a JSP usually extends HttpServlet. If you really want to have your JSP implement an interface, you could do something like

public abstract class
my.package.MyJSP extends HttpServlet implements MyInterface {

}

... and then use "my.package.MyJSP" in a "page extends" directive as shown above.

The caveat to this is that some Web containers will generate their own subclasses of HttpServlet, presumably for some kine of optimization, and using the "page extends" directive will sabotage this scheme. It should still work, it just won't include the fancy footwork your Web container intended to do.

2009-05-01

Getting the 'wicket:id' attribute to validate

Wicket is great. The "wicket:id" attribute is all that needs to be added to a tag to place it under program control.

If you have a finicky validator (or any validator), it may object to the attribute, which isn't part of (X)HTML.

The solution is to add a namespace declaration, like this:

<html xmlns:wicket="http://wicket.apache.org">

Mixing Java and Scala in an Eclipse Project

If you start a project off as a Scala project, then it's OK to mix in some Java source. Everything will be compiled as appropriate, and library references will work out too.

But for some projects, such as the "Dynamic Web Project," that's not an option. You must convert it to a Scala project after it's created as a Java project.

Fiddling with the contents of .project manually didn't get me anywhere.

The correct procedure, as found on Nabble, is:

As a general rule you should convert Java projects to Scala projects
by using the "Add Scala Nature" package explorer context menu action
unless you know what you're doing.

2009-04-18

Simulating a manual window close

w.getToolkit().getSystemEventQueue().postEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING));

obtained (with thanks) from: http://forums.java.net/jive/thread.jspa?threadID=35565

This will fire the WindowClosing event, so you can execute any action you may have bound to that event.

2009-02-18

German Keyboard, VMWare, Ubuntu host

There are lots of things that can go wrong with this.

The most helpful hints I could find were here and here.

Following this advice, I edited my ~/.vmware/config file to look like this:

xkeymap.nokeycodeMap = true
xkeymap.keysym.ISO_Level3_Shift = 0x138
xkeymap.keysym.braceleft = 0x1a
xkeymap.keysym.braceright = 0x1b


I think the second line is the most important for my German keyboard, as it maps the AltGr key.

2009-01-02

TightVNC Port Number Gotcha

TightVNC is great if you want to remote-control someone else's PC without resorting to MS' Remote Desktop solution.

Something that cost me about an hour's worth of frustration, though, is their way of specifying an alternative to the standard port (5900):

You either

  1. specify an alternate screen number (a small integer, e.g. 5 means screen 5 means port 5905); or

  2. explicitly specify an alternate port, e.g. 5905 .


Alternative 1 is selected with a colon between the host address and the screen number, e.g.

66.66.66.66:5

To specify an alternate port, you need to insert two colons:

66.66.66.66::5905

Because colons are just tiny freckles on the screen, especially in proportional fonts, this is easy to overlook in the documentation. Many other utilities (and URLs) use single colons before a port number, so habit has us do the wrong thing by default.

2008-12-20

Autocompletion in the Windows command processor

Registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor (for all users)
or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor (for the current user)

Set
CompletionChar to 9 to have TAB complete file names,
PathCompletionChar to 9 to have TAB complete folder names.

Nuff said.

2008-12-14

HTML Help Gotcha on toc.hhc

If you're trying to create MS HTML Help files (.CHM) programmatically, you may need to generate your own TOC.

The documentation available from Microsoft does its best to keep you in the dark: They tell you how to generate it in Help Workshop using their point-and-click GUI. It's serviceable but not much fun to use. No wonder there's such a huge cottage industry of MS Help front ends!

Paul Wise bravely documents what he could re-engineer about the innards of the .CHM file but only devotes a rather short section to the Sitemap format of the TOC, which I quote here:

These formats are based on HTML and use the following doctype:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

The <HEAD> tag contains a <meta> tag providing information on the program that generated the files and a comment indicating the version of the file. e.g.:

<meta name="GENERATOR"content="Microsoft® HTML Help Workshop 4.1">
<!-- Sitemap 1.0 -->

The <BODY> tag contains an <OBJECT> tag that stores properties of the file in <param> tags, followed by a <UL> tag, whose <LI> tags have <OBJECT> tags that store the properties of the Contents/Index items in <param> tags. e.g.:

<BODY>
<OBJECT type="text/site properties">
<param name="Property Name" value="Property Value">
…
</OBJECT>
<UL>
<LI> <OBJECT type="text/sitemap">
<param name="Property Name" value="Property Value">
…
</OBJECT>
…
</UL>
</BODY>

Note that the Property Names and Property Values and tags are not case-sensitive, but HHW will always write all three in the default capitilization, when appropriate.

Note that the tags are mostly in uppercase and the <LI> tag is not closed; this is in compliance with the doctype.

I spent some days generating the TOC from a different structure. To help with eyeball debugging, my HTML was nicely indented. I started a new line for each tag - not entirely unreasonable. Without the indentation, here's an example of what I created:
<HTML>
<BODY>
<UL>
<LI>
<OBJECT type="text/sitemap">
<param name="Name" value="Heading 1">
<param name="Local" value="h1.htm">
</OBJECT>
</LI>
</UL>
</BODY>
</HTML>

Try as I might, HHW (the Workshop) would not display such a TOC, and HHC (the Compiler) would not produce a working .CHM from it. I spent a long time figuring out what's needed to make it work, as in the following:
<HTML>
<BODY>
<UL>
<LI><OBJECT type="text/sitemap">
<param name="Name" value="Heading 1">
<param name="Local" value="h1.htm">
</OBJECT>
</LI>
</UL>
</BODY>
</HTML>

This appears to be one of the best kept secrets of the HTML Help generating industry:

If you don't put <LI> on the same line as <OBJECT>, the TOC parser will fail!

So the accepted format is essentially an HTML Unordered List of Objects with details in Params, give or take a horrible bug in the scanner/parser.

On the bright side, in my experience the following bits are not essential:

  • As Paul states, tags and even attribute names are accepted in upper or lower case.

  • The stuff in the <HEAD> isn't needed and can be dispensed with.

  • The text/site properties OBJECT is only needed if you want to fiddle with the options

  • Tags may be consistently closed (XML fashion), including those that HTML is inconsistent about, such as <meta> and <param. Similarly, it's OK to have closing </LI>'s.

2008-12-12

Running HTML Help Workshop under Wine

Help Workshop is a Microsoft product that creates somewhat compressed help files (.CHM) for use in/with MS programs. The Workshop "main" is a GUI application but there's also a standalone compiler.

Installed and run under Wine in a modern Linux (Ubuntu 8.04), hhw.exe and hhc.exe kept telling me:
HHC5010: Error: Cannot open "C:\windows\temp\TFS483e.tmp". Compilation stopped.

I found a simple fix at The MRPT Project:

You are advised to open "Wine Configuration," set up new configs for hhw.exe and/or hhc.exe . For either or both, in the Libraries tab, add a new override for "itss," then edit it to select "native."

My Wine installation already had an itss.dll in .wine/drive_c/windows/system32, but it was a tiny thing a little over 4 KB in size. I found a "real" itss.dll on the 'net of about 134 KB and plunked that over the installed one.

Both hhw and hhc work for me now.

2008-11-16

Tomcat permissions

As packaged with Ubuntu 8.04, Tomcat is set up pretty tight on security. The configured permissions are quite minimal, so many things you'd want to do in your servlets or JSPs needs to be explicitly permitted.

This isn't necessarily surprising; but it can be a pain.

First, some helpful links: The Security Manager HOW-TO in Apache's Tomcat documentation explains the basics. For specifics on the format of permission entries, see Sun's documentation on Default Policy Implementation and Policy File Syntax.

Notes:


  • Tomcat's policy settings are (on my Ubuntu box) in /usr/share/tomcat5.5/conf/catalina.policy. But heed the warning in the file's header: If your system is Debian-esque (and that includes Ubuntu) then that file is auto-generated from a set of files in conf/policy.d, and those are the ones you want to be editing. Permissions you want to add for your web apps will likely best fit in 50user.policy.


  • The policy files are concatenated and the settings initialized when Tomcat starts. Hence, you need to restart Tomcat in order for permission changes to have an effect.


  • The codeBase string is a URL, so it always takes forward slashes. File names for FilePermission may be operating system dependent, so you should use ${file.separator} instead there.


  • As explained in the Sun doc, an asterisk (*) in a path for FilePermission (roughly) means "everything in this directory", while a dash (-) means "everything in this directory and recursively in all subdirectories". Likewise, the beginning of a host address for SocketPermission may be wildcarded with an asterisk. In the extreme case, the entire host address may be an asterisk and so will apply to "any host".


  • If you're having trouble getting permissions to take effect, you can try narrowing down the problem by making either the codeBase universal (surprisingly, the "codeBase" descriptor is optional, so it's quite legal to have a stanza that starts with "permit {" or the permission all-encompassing: that would be "java.security.AllPermission". Once you get stuff working with this gaping security hole, you will want to go back and try to tighten it up again.

2008-11-15

Document is null

I tried to read an XML configuration file into a DOM, like so:

InputStream configInputStream = this.getClass().getClassLoader().getResourceAsStream(CONF_FILE_NAME);
log("configInputStream = " + configInputStream);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(configInputStream);
log("Found and read configuration: " + doc);
configInputStream.close();

...and the log said:
INFO: ToonGrator: Found and read configuration: [#document: null]

I guess the square brackets and the extra text should have tipped me off, but I sure thought
I had read in a null document!

It isn't really. It turns out that the root (or document) node always contains no text, so
whatever its toString() returns will say "null". Oh well, back to work!

2008-11-12

Writing files from JavaScript

In Internet Explorer, you can use the ActiveXObject "microsoft.xmldom" to load an XML file into a DOM that can be inspected and manipulated from JavaScript. So far so good. But what if you want to write an XML file to the local file system? XmlDom has a save() method and the argument lets you specify a local file path. But in IE6 and later, the attempt will always fail.

The 'net is full of forum posts with frantic pleas for help with titles like "XML DOM save - File Permission denied". In almost all cases, the answers fell into the following categories:

"Tough luck, that's the way it is" / "the cookie crumbles."

True enough, but not helpful.

"You need to have write permission on the folder you're writing to!"

True enough, but I'll bet everyone with half a brain checked that before posting. Even if that was the problem, you'd run up against the previous one.

"I have the same problem. Please email me the answer!"

Me too!

"You can't do that from HTML, you need a HTA

True enough, but if the requester could get a user to download and execute an application he wouldn't have this problem in the first place.

"In ASP on the server you do this..."

That doesn't help with saving files on the client's file system.



It was a long time before I came across a post that mentioned FileSystemObject. It turns out that while xmldom.save() is never allowed to write to the local file system (apparently no amount of tweaking any permissions will change that), FileSystemObject can create, read, write and even delete files, subject to permissions given in IE's Internet Options.

It's no big deal to pull the XML from the DOM as a String and to save it using a TextStream object created by FileSystemObject.CreateTextFile(). Here's a code sample of mine that does it:


function save2()
{
var xmlDoc = new ActiveXObject("microsoft.xmldom");
xmlDoc.load(path + "stuff.xml");
alert("stuff.xml loaded");
fso = new ActiveXObject("Scripting.FileSystemObject");
f2 = fso.CreateTextFile(path + "stuff2.xml", true);
f2.write(xmlDoc.xml);
f2.Close();
alert("stuff2.xml saved");
}


I surmise that more readers of those forums knew the "right" answer but chose not to tell because they suspected malicious intent on part of the requesters. When you can write to the user's file system you can do many evil things.

My take on this is: Any user surfing the Web with IE and permissions set to "trusting" is asking for trouble anyway; and the more professional malware authors already know how to exploit this. Microsoft's choice to never allow XmlDom to save looks silly in view of the fact that there's a perfectly workable back door.

My own use of this feature is legitimate, of course: I'm working with a JavaScript application that wants to store some user settings on the user's machine. More information than will fit into a cookie, and there's no server to persist the information on. Also, it's a closed environment, even to the user, with no Internet connection, so it can safely run with full permissions.