December 3, 2010

Wicket installation

Update: I finally got around to writing the second part, about setting Wicket up with Tomcat instead of relying solely on the embedded Jetty server. See it here.


Downloaded JDK 6_22
Downloaded Maven 3.01
Installed JDK to C:\Program Files\Java\jdk1.6.0_22
Unzipped maven to C:\Program Files\apache-maven-3.0.1
Updated system environment variables:

- M2
C:\Program Files\apache-maven-3.0.1
- M2_HOME
%M2_HOME%\bin = C:\Program Files\apache-maven-3.0.1\bin
- JAVA_HOME
C:\Program Files\Java\jdk1.6.0_22
- M2_REPO
C:\Users\Programmer\.m2\repository

Followed instructions at Wicket quickstart
Generated this Maven command from quickstart:

mvn archetype:create -DarchetypeGroupId=org.apache.wicket -DarchetypeArtifactId=wicket-archetype-quickstart -DarchetypeVersion=1.4.1 -DgroupId=com.mycompany -DartifactId=projName

Ran above Maven command from command line
Relevant files, including Wicket source, were downloaded automatically (based on POM?)
Ran mvn eclipse:eclipse to create an Eclipse project based on above
Imported project into Eclipse with File > Import..., Existing Projects

Ran Start.java in the test folder and went to http://localhost:8080 — success.

Wanted to add Wicket Extensions support.
Manually adding JAR file to to M2_REPO directory didn't work.

Current status:
Adding a dependency to the POM is probably right (there's even a similar dependency in there but commented out), but how will Maven understand that the new dependency needs to be added? Merely uncommenting and running Start does nothing.

Resolved: Just run mvn clean dependency:copy-dependencies after updating the POM. There's probably a better way to do this, though. Then configure the build path by using Add Variables... (not Add JARs), select M2_REPO, press Extend, find the desired JAR (in this case, Wicket Extensions).

Current status:
Need to figure out how to make this worth with Tomcat instead of relying on the embedded Jetty server all the time.

August 23, 2010

Why arrow code is bad

I, like Jeff Atwood, don't like arrow code.

But is arrow code actually bad, or just unsightly? It's bad. Jeff mentions cyclomatic complexity but doesn't describe it; so see Wikipedia.

In particular,

[Most of the relevant] studies find a strong positive correlation between cyclomatic complexity and defects: modules that have the highest complexity tend to also contain the most defects.

August 10, 2010

How Ryan Tomayko explained REST to his wife

The web is built on an architectural style called REST. REST provides a definition of a resource, which is what [URLs] point to.

A web page is a representation of a resource. Resources are just concepts. [URLs] tell the browser that there’s a concept somewhere. A browser can then go ask for a specific representation of the concept. Specifically, the browser asks for the web page representation of the concept.

Full post on Ryan's blog

July 13, 2010

Vista fonts compared to older fonts

The "Vista fonts" are Cambria, Calibri, Candara, Consolas, Constantia and Corbel. A good piece on them is provided by hunlock.com here.

July 12, 2010

Package becomes unrecognized in Eclipse

Error:
Saving a Java source file in Eclipse causes the errors "[class] cannot be resolved to a type" and "The import org.oasis_open.docs.[whatever] cannot be resolved" for classes in a package that was previously recognized.

Solution:
Open the context menu for the affected package in Package Explorer, select Build Path > Configure Build Path... and go to the "Order and Export" tab. Make sure custom classes are at the top, third-party files are in the middle and the JRE is at the bottom of the list. Select OK and refresh the affected files/packages.

July 8, 2010

Putting a head tag below a body tag

It is possible to put <head> tags underneath <body> tags. Why do this? One reason is to make cache instructions work better, as described by Microsoft here.

Another is described in High Performance Web Sites: Rule 6 – Move Scripts to the Bottom by Steve Souders, Yahoo!'s Chief Performance Yahoo!

With stylesheets, progressive rendering is blocked until all stylesheets have been downloaded. That’s why it’s best to move stylesheets to the document HEAD, so they get downloaded first and rendering isn’t blocked. With scripts, progressive rendering is blocked for all content below the script. Moving scripts as low in the page as possible means there's more content above the script that is rendered sooner.

The second problem caused by scripts is blocking parallel downloads.

July 6, 2010

The Java heap

The young generation consists of eden plus two survivor spaces. Objects are initially allocated in eden. One survivor space is empty at any time, and serves as a destination of the next, copying collection of any live objects in eden and the other survivor space. Objects are copied between survivor spaces in this way until they are old enough to be tenured, or copied to the tenured generation.

-Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine by Sun

The Java HotSpot VM defines two generations: the young generation (sometimes called the "nursery") and the old generation. The young generation consists of an "Eden space" and two "survivor spaces." The VM initially assigns all objects to the Eden space, and most objects die there. When it performs a minor GC, the VM moves any remaining objects from the Eden space to one of the survivor spaces. The VM moves objects that live long enough in the survivor spaces to the "tenured" space in the old generation. When the tenured generation fills up, there is a full GC that is often much slower because it involves all live objects. The permanent generation holds all the reflective data of the virtual machine itself, such as class and method objects.

-Using JConsole by Sun

See figure at either link above (both use the same figure).

Mark-and-Sweep Garbage Collection, used in Tenured Generation GC
Stop-and-Copy Garbage Collection, used in Young Generation GC
The Copy Algorithm, used in the Stop-and-Copy method of GC

June 28, 2010

Create and print a simple XML document in Java using javax.xml.transform.Transformer


package pkg;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Bar
{
public static void main(String[] args)
{
List properties = new ArrayList();
properties.add(new DummyObject("n1", "t1", "v1"));
properties.add(new DummyObject("n2", "t2", "v2"));
properties.add(new DummyObject("n3", "t3", "v3"));
properties.add(new DummyObject("n4", "t4", "v4"));
properties.add(new DummyObject("n5", "t5", "v5"));
properties.add(new DummyObject("n6", "t6", "v6"));
properties.add(new DummyObject("n7", "t7", "v7"));
properties.add(new DummyObject("n8", "t8", "v8"));
properties.add(new DummyObject("n9", "t9", "v9"));

// Create XML document tree
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document documentTree = null;
Element dummyParent = null;
try
{
db = dbf.newDocumentBuilder();
documentTree = db.newDocument();
dummyParent = documentTree.createElement("DummyParent");
documentTree.appendChild(dummyParent);

for (DummyObject property : properties)
{
// Create XML tags for the property
Element propertyNode = documentTree.createElement("Property");
Element nameNode = documentTree.createElement("Name");
Element typeNode = documentTree.createElement("Type");
Element valueNode = documentTree.createElement("Value");

// Populate the property's XML tags
nameNode.setTextContent(property.getName());
typeNode.setTextContent(property.getType());
valueNode.setTextContent(property.getValue());

// Add the data to the property node
propertyNode.appendChild(nameNode);
propertyNode.appendChild(typeNode);
propertyNode.appendChild(valueNode);

// Add the property node to the XML tree
dummyParent.appendChild(propertyNode);
}

DOMSource source = new DOMSource(documentTree);
StreamResult result = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(source, result);
}
catch (ParserConfigurationException e)
{
System.out.println("D'oh! Creating the document failed.");
System.out.println(e.getMessage());
}
catch (TransformerException e)
{
System.out.println("D'oh! Transformer failed.");
System.out.println(e.getMessage());
}
}
}

class DummyObject
{
String name;
String type;
String value;

public DummyObject()
{
super();
}

public DummyObject(String n, String t, String v)
{
name = n;
type = t;
value = v;
}

public String getName()
{
return name;
}

public String getType()
{
return type;
}

public String getValue()
{
return value;
}
}

June 1, 2010

[Tom] Duff's Device

Duff's Device is mentioned in the JLS section about switch statements. The nitty-gritty is explained at this StackOverflow answer.

Sample code:

package pkg;

public class Foo
{
public static void main(String args[])
{
int numTimesToCallMethod = 20;
int numTimesToRunWhile = (numTimesToCallMethod + 7) / 8;

switch (numTimesToCallMethod%8)
{
case 0:
do {
IllHaveADuffYouHaveOneToo(); // Great C hack, Tom,
case 7: IllHaveADuffYouHaveOneToo(); // but it's not valid here.
case 6: IllHaveADuffYouHaveOneToo();
case 5: IllHaveADuffYouHaveOneToo();
case 4: IllHaveADuffYouHaveOneToo();
case 3: IllHaveADuffYouHaveOneToo();
case 2: IllHaveADuffYouHaveOneToo();
case 1: IllHaveADuffYouHaveOneToo();
} while (--numTimesToRunWhile > 0);
}
}

public static void IllHaveADuffYouHaveOneToo()
{
System.out.println();
}
}


MyEclipse 8.5 shows two errors at the semicolon immediately before "Great C hack...":
Multiple markers at this line
- Syntax error, insert "while ( Expression ) ;" to complete DoStatement
- Syntax error, insert "}" to complete Block

April 28, 2010

CMIS notepad

CMIS 1.0 specification (HTML):
http://docs.oasis-open.org/cmis/CMIS/v1.0/cs01/cmis-spec-v1.0.html

CMIS Relationship object:
http://docs.oasis-open.org/cmis/CMIS/v1.0/cs01/cmis-spec-v1.0.html#_Toc243905402

CMIS Relationship Service:
http://docs.oasis-open.org/cmis/CMIS/v1.0/cs01/cmis-spec-v1.0.html#_Toc243905479

The Relationship Services (getObjectRelationships) are used to retrieve the dependent Relationship objects associated with an independent object.

April 21, 2010

Weak references in Java

there are actually four different degrees of reference strength: strong, soft, weak, and phantom

The important part about strong references — the part that makes them "strong" — is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection.

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.

Understanding Weak References by Ethan Nicholas

April 13, 2010

Show/hide .classpath and other files in Eclipse Package Explorer

Click on the down arrow icon at the top of the toolbar, and open the Filters menu.

Firebug does not reload JavaScript properly

Workaround is to clear all breakpoints in the JavaScript file and Shift+F5 or Shift+reload the page.

See Firebug issue 207.

March 30, 2010

XML namespaces intro

XML:
Simple example without schema involvement
FILL IN

XML Schema:
targetNamespace

"targetNamespace is used in a schema to specify the namespace that the schema is intended to define" -David Peterson, at JavaRanch

"Each schema document has exactly one target namespace." -XML in a Nutshell

default namespace

noNamespaceSchemaLocation
noNamespaceSchemaLocation: schema to reference for elements that have no namespace prefix?
"The noNamespaceSchemaLocation attribute references an XML Schema document that does not have a target namespace. "

schemaLocation

Interface between XML document and its schema:
FILL IN

Note from w3schools:
The namespace URI is not used by the parser to look up information.

The purpose is to give the namespace a unique name. However, often companies use the namespace as a pointer to a web page containing namespace information.

March 16, 2010

Getting started with Groovy

http://docs.codehaus.org/display/GROOVY/Install+Groovy-Eclipse+Plugin
http://docs.codehaus.org/display/GROOVY/Create+Your+First+Groovy+Project

CSS positioning

http://stackoverflow.com/questions/2451043/change-an-absolutely-positioned-webpage-into-a-centered-one/2451067#2451067

FINISH POST

Groovy intro: range operator and looping

The operator .. in Groovy is called the range operator, not the dot-dot operator or two-dot operator. It's used to define ranges for things like loops; for(1..8){foo()} will loop eight times.

Ref: http://groovy.codehaus.org/Collections#Collections-Ranges

New Groovy-style loops are a little more powerful than Java loops, too:
http://groovy.codehaus.org/Looping

javadoc.exe man page

http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html

Generating Javadoc using MyEclipse

It seems that some versions of MyEclipse don't have the "Generate Javadoc..." option under the main Project menu that "regular" Eclipse does, at least MyEclipse 7.5. The facility for generating Javadoc is still somewhere; one workaround way to access it is by opening the help menu, searching for "javadoc" and opening the second result, "Javadoc Generation." That help file has a link to the Javadoc Generation wizard.

March 15, 2010

soapUI is powerful

soapUI (on SO) has its own API of built-in methods. It allows for scripting in Groovy.

Bonus link: soapUI tips and tricks, including a runTestStepByName-esque method.

Intro to Groovy

http://www.javalobby.org/articles/groovy-intro1/

March 8, 2010

Setting Eclipse diff tool to ignore whitespace

Open Window > Preferences from the menu bar
Select General > Compare/Patch in the left-side tree menu
Check "Ignore white space"
Press Apply, then OK

(from http://masa-paris.spaces.live.com/Blog/cns!F61AACB5DACD22A7!884.entry)

March 5, 2010

XML targetNamespace

"When we want to [validate an XML doc], we need to identify which element and attribute declarations and type definitions in the schemas should be used to check which elements and attributes in the instance document. The target namespace plays an important role in the identification process."
-from w3c here

Qualified and qualified elements are discussed on this page under the section "Qualified or Unqualified."

Qualified: "all the elements and attributes in the instance must have a namespace, which ... adds namespace complexity"
Unqualified: "only the globally declared elements and attributes in the instance must have a namespace, which ... hides the namespace complexity from the instance"

The meaning of global is described on this page:

"When an element declaration is a child of the xs:schema element, the declared element is global. Global elements can be referenced by other element declarations, allowing for element reuse."

More on global vs. local here.

March 2, 2010

Validating XML against schemas in Java

XML validation with namespaces will not work properly unless the DocumentBuilderFactory has namespace awareness turned on manually, via setNamespaceAware.

January 25, 2010

Intro to XPath

Helpful XPath syntax reference from W3

Sample code based loosely on this Java2S example:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParserAlpha
{
private static final String SOURCE = "C:/someFolder/xmlFile.xml";
private static final String EXPR = "*";

public static void main(String[] args)
{
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = EXPR;
InputSource inputSource = new InputSource(SOURCE);

NodeList nodes = null;
int j = -1;
try
{
nodes = (NodeList) xpath.evaluate(xpathExpression, inputSource, XPathConstants.NODESET);
// NODESET maps to interface org.w3c.dom.NodeList
j = nodes.getLength();

for (int i = 0; i < j; i++) { System.out.println(nodes.item(i).getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } } }


Other values of EXPR and what they're good for:
/Report/PublicationMetadata/DescriptiveMetadata/Title/@* - All attribute values of the title element (but not the attribute names)

TODO: FINISH POST

January 13, 2010

Intro to working with XML using Java

Rob Lybarger wrote a great intro article about this, the link skips to page two of five: Working with XML and Java

Syntactic sugar

Syntactic sugar on Wikipedia

"[Syntactic sugar is] syntax designed to make things easier to read or to express, while alternative ways of expressing them exist. It makes the language 'sweeter' for humans to use...." -Wikipedia

January 7, 2010

Array index behavior in Java

int indexFor1D = 3;
int indexFor2D = 1;
int [] array1D = { 5, 6, 7, 8, 9 };
int [][] array2D = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};

System.out.println("From 2D: " + array2D[indexFor2D++][indexFor2D++]);
System.out.println("indexFor2D: " + indexFor2D);

array1D[indexFor1D++] = indexFor1D;
System.out.println("indexFor1D: " + indexFor1D);
System.out.print("New 1D: ");
for(int tmp : array1D)
System.out.print(tmp);


produces output

From 2D: 5
indexFor2D: 3
indexFor1D: 4
New 1D: 56749

Nerd Sniping or: Finally Always Wins, Unless You Crash The Machine Beforehand.

try {
return true;
} finally {
return false;
}


http://stackoverflow.com/questions/1995113/strangest-language-feature/2005435#2005435

January 6, 2010

Rules for bits in Java

All integer literals are, by default, ints in Java. All floating point literals are, by default, doubles. If a value larger than allowed is put into a given primitive type, the leftmost bits are discarded. So,

char c = (char) 65656; // Binary 00000000000000010000000001111000
byte i = (byte) 130; // Binary 00000000000000000000000010000010

A char is 16 bits, so it is set to 0000000001111000, which equals 1111000, which is 120, which in turn is the character 'z'; a byte is eight bits, so it is set to 10000010. Since the first bit is a sign bit, this actually equals -126. (By two's complement, 10000010 = -(01111101 + 1) = -(01111110) = -126.)

Division by zero in Java

Incredibly, the following code will compile without any problems:


int x = 7/0;
System.out.println(x);

int y = 0;
int z = 7/y;
System.out.println(z);


When the inevitable runtime error occurs, it appears as an ArithmeticException; there is no such thing as DivideByZeroException.

January 5, 2010

Increment and decrement for array indices in Java

This code


int anIndex = 1;
int [][] anArray = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
System.out.println("Number: " + anArray[anIndex++][anIndex++] + ".");


prints out "Number: 5." That's anArray[1][2]; anIndex is incremented after each index, so it ends up at 3 by the end of the code fragment.

Concatenation to strings in Java


System.out.println("" + 1 + 2);
System.out.println(1 + "" + 2);
System.out.println(1 + 2 + "");


results in

12
12
3

Java instanceof operator

instanceof checks true runtime values. So, the following code would print:


Object o = new LinkedList();
if(o instanceof LinkedList)
System.out.println("yep");


This is not the same behavior as method lookup (find the fancy name for this). This example would produce an error:


List theList = new Queue();
theList.enqueue(new Object());

Class initialization in Java

"Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down." -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)

Class loading time is the same as initialization time, which is described right at the top of section 12.4 of the Java Language Specification.

What happens if more than one class contains static init blocks? Are static init blocks guaranteed to run? My question at Stack Overflow covers these questions.

What about multiple instances of a class? As expected, the static initialization blocks do NOT run again. Modifying main() from the link above to this:


System.out.println("START");
new Child();
System.out.println("MIDDLE");
new Child();
System.out.println("END");


produces this output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
MIDDLE
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END

Initialization blocks in Java

Code:

public class LoadTest
{
public static void main(String[] args)
{
System.out.println("START");
new Child();
System.out.println("END");
}
}

class Parent extends Grandparent {
// Instance init block
{
System.out.println("instance - parent");
}

// Constructor
public Parent() {
System.out.println("constructor - parent");
}

// Static init block
static {
System.out.println("static - parent");
}
}

class Grandparent {
// Static init block
static {
System.out.println("static - grandparent");
}

// Instance init block
{
System.out.println("instance - grandparent");
}

// Constructor
public Grandparent() {
System.out.println("constructor - grandparent");
}
}

class Child extends Parent {
// Constructor
public Child() {
System.out.println("constructor - child");
}

// Static init block
static {
System.out.println("static - child");
}

// Instance init block
{
System.out.println("instance - child");
}
}


Output:
START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END

Generic methods in Java


public static void main(String[] args) {
genericMethod("abc");
}

static void overloadedMethod(Object o) {
System.out.println("overloadedMethod(Object) called");
}

static void overloadedMethod(String s) {
System.out.println("overloadedMethod(String) called");
}

static void overloadedMethod(Integer i) {
System.out.println("overloadedMethod(Integer) called");
}

static <T> void genericMethod(T t) {
overloadedMethod(t);
}


produces output "overloadedMethod(Object) called"; this is because the generic method doesn't know what kind of argument will be passed in at compile time [DBL-CHECK REASON]

Characters in Java

A char in Java is technically just an unsigned 16-bit number. The following code works just fine...


// 65656 - 1 - 120 = 65535, the max 16-bit unsigned range
char crazyChar = (char) 65656;
System.out.println("(char) 65656: " + crazyChar);


... and produces output "(char) 65656: x" (the ASCII/Unicode value for x is 120).

This is also perfectly legal, if not meaningful:

char crazierChar = (char) -552;

Note that casts are required for both of these snippets.

Default initialization in Java

In Java, class variables get initialized to default values. This code...

public class Test {
private static String _string;
private static byte _byte;
private static short _short;
private static int _int;
private static long _long;
private static float _float;
private static double _double;
private static boolean _boolean;
private static char _char;

public static void main(String[] args) {
System.out.println("str " + _string);
System.out.println("byt " + _byte);
System.out.println("sht " + _short);
System.out.println("int " + _int);
System.out.println("lng " + _long);
System.out.println("flt " + _float);
System.out.println("dbl " + _double);
System.out.println("bln " + _boolean);
System.out.println("chr " + _char);
}
}


...produces this output...

str null
byt 0
sht 0
int 0
lng 0
flt 0.0
dbl 0.0
bln false
chr [the non-printable character U+0000]

Unlike class variables, method-local variables are NOT automatically initialized. This code will produce a compile-time error ("the local variable anotherInt may not have been initialized"):

int anotherInt;
System.out.println(anotherInt);


On the other hand, the compiler won't catch non-initialized class objects; this code, after the earlier snippet, compiles just fine but will cause a NullPointerException at runtime:

if ("impossible".equals(_string)) {
int x = 5;
}

January 3, 2010

TweakUI

Microsoft has a somewhat famous PowerToy for Windows XP called TweakUI. It allows users to play with several user interface settings that are built into XP but aren't easily accessible out of the box. It's available at

http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx

Turns out there's an equivalent tool for Windows Vista and 7 — though not an official Microsoft product — available at

http://www.thewindowsclub.com/ultimate-windows-tweaker-v2-a-tweak-ui-for-windows-7-vista#more-1957

The Quake 3 fast inverse square root function

http://www.beyond3d.com/content/articles/8/

Programming fonts

http://www.codinghorror.com/blog/archives/000157.html