<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>T=Machine &#187; java tutorials</title>
	<atom:link href="http://t-machine.org/index.php/category/java-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://t-machine.org</link>
	<description>Internet Gaming, Computer Games, Technology, MMO, and Web 2.0</description>
	<lastBuildDate>Tue, 20 Jul 2010 09:43:12 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Writing games in Korean &#8211; part 2</title>
		<link>http://t-machine.org/index.php/2008/04/04/writing-games-in-korean-part-2/</link>
		<comments>http://t-machine.org/index.php/2008/04/04/writing-games-in-korean-part-2/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 16:15:18 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[computer games]]></category>
		<category><![CDATA[games design]]></category>
		<category><![CDATA[java tutorials]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://t-machine.org/index.php/2008/04/04/writing-games-in-korean-part-2/</guid>
		<description><![CDATA[Using a custom font renderer that lets me position text exactly where I want it, I put together a simple game that teaches you to count from 1 to 10 in Korean characters.

First, you HAVE to manually download the Korean font I&#8217;m using (because I don&#8217;t think I can legally include it in the executable [...]]]></description>
			<content:encoded><![CDATA[<p>Using a custom font renderer that lets me position text exactly where I want it, I put together a simple game that teaches you to count from 1 to 10 in Korean characters.</p>
<p><a href='http://t-machine.org/wp-content/uploads/2008/04/korean-numbers-test-ss-1.PNG' title='Screenshot of numbers test'><img src='http://t-machine.org/wp-content/uploads/2008/04/korean-numbers-test-ss-1.PNG' alt='Screenshot of numbers test' /></a></p>
<p>First, you HAVE to manually download the Korean font I&#8217;m using (because I don&#8217;t think I can legally include it in the executable file :( )</p>
<p>http://www.i18nl10n.com/fonts/UnBatang.ttf</p>
<p>NOTE: you MUST (windows is rubbish) do &#8220;Save to&#8221; and select C:\Windows\Fonts (this causes windows to automagically &#8220;install&#8221; the font) &#8211; I can&#8217;t remember how to install new fonts on Linux or OS-X, but it should work fine with both of those OS&#8217;s too.</p>
<p>Then just stick the two attached files in a directory somewhere, and double-click on the one called korean-numbercounter-all.jar</p>
<p><a href='http://t-machine.org/wp-content/uploads/2008/04/log4j.jar' title='Additional library (log4j) needed to run Korean numbers test'>Essential library (download this)</a><br />
<a href='http://t-machine.org/wp-content/uploads/2008/04/koreantest-numbercounter-all.jar' title='Main executable for Korean numbers test'>Main file (download this to same directory as the library file, and run this file)</a></p>
<p>NB: this is mainly just a proof of concept to test my rendering code, I&#8217;ve got a couple of other simple &#8220;games&#8221; like this I&#8217;ve knocked up as tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2008/04/04/writing-games-in-korean-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing games in Korean &#8211; part 1</title>
		<link>http://t-machine.org/index.php/2008/03/28/writing-games-in-korean-part-1/</link>
		<comments>http://t-machine.org/index.php/2008/03/28/writing-games-in-korean-part-1/#comments</comments>
		<pubDate>Fri, 28 Mar 2008 18:47:53 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[computer games]]></category>
		<category><![CDATA[dev-process]]></category>
		<category><![CDATA[java tutorials]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://t-machine.org/index.php/2008/03/28/writing-games-in-korean-part-1/</guid>
		<description><![CDATA[First, check whether I can actually render Korean characters. I know that Unicode supports nearly all of the glyphs (or, more correctly it seems, &#8220;ideographs&#8221;) needed for Chinese, Japanese, Korean (typically abbreviated as &#8220;CJK&#8221;) &#8211; but I also know that MS Windows fonts are infamous for missing some/most/all of the unicode characters (there are tens [...]]]></description>
			<content:encoded><![CDATA[<p>First, check whether I can actually render Korean characters. I know that Unicode supports nearly all of the glyphs (or, more correctly it seems, &#8220;ideographs&#8221;) needed for Chinese, Japanese, Korean (typically abbreviated as &#8220;CJK&#8221;) &#8211; but I also know that MS Windows fonts are infamous for missing some/most/all of the unicode characters (there are tens of thousands of them, so this is not all that surprising &#8211; except that Microsoft has been shipping OS&#8217;s localized to those countries for many years now, so I&#8217;d hoped maybe they would include at least ONE &#8220;CJK + Latin&#8221; font on all machines by now, no? No; they don&#8217;t).</p>
<p>Quick test program using Java (NB: java one of the easier languages for this because it was invented late enough that Unicode had settled down, and so it has extremely good Unicode support built-in to the core libraries, unlike C++ et al. By default, Java uses unicode almost everywhere, so I don&#8217;t need to debug unicode support, yay!):</p>
<p>NB: &#8230;but then when I tried it I quickly discovered a problem. I quickly gave up on the obvious route, so might have missed a workaround, but&#8230; I could have done this using Java&#8217;s built-in GUI toolkit (Swing), which supports using any font as a text label. However, it seems there&#8217;s a design flaw in Swing that&#8217;s been around since 1997 (yes, folks, 11 years and counting): the only component that can have the font changed &#8211; JLabel &#8211; which is a &#8220;general-purpose&#8221; label for any GUI component (good idea!) &#8230; is incompatible with the only component capable of being a button &#8211; JButton &#8211; which is a &#8220;general-purpose&#8221; button. Crap. If I&#8217;m not missing something here, with one small piece of poor API design, Sun have made their *almost* international-friendly GUI system almost completely useless for multi-language GUIs. Just to be clear: it&#8217;s not specifically internationalization they&#8217;ve broken here: its a general issue &#8211; any forms of customized rendering cannot use the JButton / JLabel combo. Why? Why, why, why would you do such a stupid thing, after going to the effort of making these generic widgets? Oh, well. Custom rendering it is&#8230;</p>
<blockquote>
<pre>
/**
 * Simple test program that renders Unicode characters from a particular font of
 * your choice, a couple of thousand at a time, automatically wrapping them based on
 * render width on screen.
 *
 * You need to manually change the font name and the start/end co-ordinates of where
 * in the unicode constellation to render.
 */

import java.awt.*;
import javax.swing.*;

public class PaintSomeUnicodeChars extends JFrame
{
	void setup()
	{
		getContentPane().add( new charPane() );
	}

	public static void main( String[] args )
	{
		PaintSomeUnicodeChars window = new PaintSomeUnicodeChars();
		window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		window.setup();
		window.pack();
		window.setSize( 600, 500 );

		window.setVisible( true );
	}
}

class charPane extends JPanel
{
	public void paint( Graphics g )
	{
		int si = 44032;
		int ei = 46000;
		g.setColor( Color.red );
		g.setFont( new Font( "Verdana", 10, 40 ) );
		g.drawString( "Chars from " + si + " to " + ei, 30, 30 );

		g.setColor( Color.black );
		g.setFont( new Font( "Lucida Sans Unicode", 10, 20 ) );

		int accumulator = 0;
		int height = 20;
		int xwidth = getWidth();
		for( int i = si; i < ei; i++ )
		{
			char[] chars = Character.toChars( i );
			String drawString = String.copyValueOf( chars );
			int advance = g.getFontMetrics().charsWidth( chars, 0, chars.length );

			if( accumulator + advance > xwidth )
			{
				accumulator = 0;
				height += g.getFontMetrics().getHeight();
			}

			g.drawString( drawString, accumulator, height );

			accumulator += advance;
		}
	}
}
</pre>
</blockquote>
<h4>Why choose Lucida Sans Unicode?</h4>
<p>Apart from the fact that it&#8217;s present on all modern Windows machines automatically, I cheated a bit and used Character Map (Start > Programs > Accessories > System Tools > Character Map) to quickly inspect each of the fonts already installed and find out which ones had lots of unicode in them. Character Map has a neat feature where it completely ignores missing characters, automatically skipping over them, so you can very quickly see if a font has lots of unicode, some, or very little.</p>
<p>Stepping through in the java app, I fairly quickly found lots of Unicode characters. success &#8211; I can correctly render arbitrary Unicode characters in java.</p>
<p>NB: important because it took a lot more lines of source than I expected; java&#8217;s built-in &#8220;char&#8221; datatype is incapable of being used to render Unicode, because it&#8217;s too small a range of values. That also means you can&#8217;t use ANY methods that take a char as argument (this is documented in the Java API docs for Character). I&#8217;d never really used the methods that take int&#8217;s as argument before&#8230;</p>
<h4>Fonts&#8230;</h4>
<p>Not really happy with the font, though, and it&#8217;s clearly missing a whole bunch of characters. Some googling for free CJK fonts found me that allegedly Arial Unicode MS would work &#8211; which comes free with Microsoft Office (which I have on one of my machines).</p>
<p>NB: the way font licensing works, it&#8217;s probably illegal to copy a font you have on one machine to another machine you own. Unless you can obtain the font from the original source (e.g. in this case by buying a second copy of MS Office).</p>
<p>Arial Unicode MS has lots of characters, but &#8230; they&#8217;re wrong. At least, one third of the ranges of Korean characters are completely useless, as far as I can tell, because whoever made this font (whoever Microsoft licensed it from?) didn&#8217;t read the spec carefully and stuck the wrong characters in from U+1100-U+11FF. More on this later&#8230;</p>
<p>Giving up on that font, I went looking for others. The first four or five I tried that didn&#8217;t look ugly were all from download sites in Japan or Korea and kept crashing on the download. I found a couple of places hosting UnBatang (&#8221;UnBatangOdal.ttf&#8221;) and claiming it was free, but the first I found where the download didn&#8217;t crash was on <a href="http://www.i18nl10n.com/fonts" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.i18nl10n.com/fonts');">http://www.i18nl10n.com/fonts</a></p>
<p>UnBatang (the name you have to use in Windows / Java from inside an application in order to load it) seems to work very well. It has nicely painted ideographs for the main range of Hangul characters/syllables, and it has *correct* glyphs for the other two ranges (although they&#8217;re a bit ugly).</p>
<h4>Unicode Hangul</h4>
<p>Specifications for official standards tend to be big. Really big.</p>
<p>Specifications for anything to do with internationalization tend to be huge.</p>
<p>Add in localization and data-transfer between different cultures, and you can expect something gargantuan.</p>
<p>So, I was really really happy to find a downloadable copy of only the CJK Chapter of the Unicode 5.0 specification (it&#8217;s still a big document!). This contains a full explanation of what Hangul is in Unicode, where to find it (yay!), and why there are not one but three separate sets of Hangul glyphs.</p>
<p>Here&#8217;s the preface to the Chapter 12 PDF I downloaded, in case you want to find the spec / electronic version yourself:</p>
<blockquote><p>
Electronic Edition</p>
<p>This file is part of the electronic edition of The Unicode Standard, Version 5.0, provided for online<br />
access, content searching, and accessibility. It may not be printed. Bookmarks linking to specific<br />
chapters or sections of the whole Unicode Standard are available at</p>
<p><a href="http://www.unicode.org/versions/Unicode5.0.0/bookmarks.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.unicode.org/versions/Unicode5.0.0/bookmarks.html');">http://www.unicode.org/versions/Unicode5.0.0/bookmarks.html</a></p>
<p>Purchasing the Book</p>
<p>For convenient access to the full text of the standard as a useful reference book, we recommend purchasing<br />
the printed version. The book is available from the Unicode Consortium, the publisher, and<br />
booksellers. Purchase of the standard in book format contributes to the ongoing work of the Unicode<br />
Consortium. Details about the book publication and ordering information may be found at</p>
<p><a href="http://www.unicode.org/book/aboutbook.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.unicode.org/book/aboutbook.html');">http://www.unicode.org/book/aboutbook.html</a>
</p></blockquote>
<h4>Unicode 5, Hangul, and Arial Unicode MS</h4>
<p>So, armed with the offical spec, I read up on Hangul. What did I find?</p>
<blockquote><p>
The Unicode Standard contains both the complete set of precomposed modern Hangul syllable<br />
blocks and the set of conjoining Hangul jamo. This set of conjoining Hangul jamo can<br />
be used to encode all modern and ancient syllable blocks.
</p></blockquote>
<p>(this is the glyphs at U+1100–U+11FF)</p>
<p>&#8220;conjoining Hangul jamo&#8221; means &#8220;these glyphs have been positioned inside their spaces in the font so that if you need to make one ideograph out of, say, four Korean letters, you just pick the top-left version of the first letter, the top-right version of the second, etc, and OVERLAY all the glyphs, and what comes out will autamatically be correctly spaced out etc&#8221;.</p>
<p>What did the author of Arial Unicode MS do?</p>
<p>Made all those glyphs take up the full available space, and centre them horizontally and vertically.</p>
<p>Why? Seriously, why? Because any application that tries to render those characters is going to render them on top of each other (according to the specification, this is the ONLY point of having those characters), and you won&#8217;t be able to read at all what the letters say.</p>
<p>If you want to render just individual letters from the Korean alphabet, there&#8217;s a different range of Unicode where you can find them all centred etc (which Arial Unicode MS also has &#8230; so it seems to be just copy/pasting internally).</p>
<p>I guess the font author just didn&#8217;t read the spec. Or I&#8217;m completely misunderstanding the spec. But the fact that UnBatang spaces the conjoining jamos out in such a way that this works as I expected it to suggests to me that it&#8217;s the Arial Unicode that&#8217;s broken&#8230;</p>
<h4>The joy of Conjoining</h4>
<p>I couldn&#8217;t get hold of the Unicode spec section on how to conjoin, because of some mimetype problems between their server and my PDA&#8217;s web browser. I figured I could probably work it out by trial and error fairly quickly.</p>
<p>I can&#8217;t remember how to spell my name in Korean yet &#8211; I know the letters, I&#8217;m just a bit flaky on what the placement of them is. So, a quick experiment, to see how easy it is to position characters using the Conjoining Jamo from UnBatang:</p>
<blockquote>
<pre>
	... constants used later - the Unicode values for the letters of my name: ...

	int a = 0x1161; // jungseong vowel
	int d = 0x1103; // choseong consonant
	int d2 = 0x11ae; // jongseong consonant
	int m = 0x1106; // choseong consonant
	int m2 = 0x11b7; // jongseong consonant
	int blank = 0x110b; // silent char you place at front if first letter is a vowel

	... the body of the paint method: ...

	g.setColor( Color.black );
	g.setFont( new Font( "UnBatang", 10, 30 ) );

	int w = 0;
	int lead = 0;
	w += renderIdeograph( g, blank, lead, 40  );
	w += renderIdeograph( g, a, lead+w, 40  );
	w += renderIdeograph( g, d2, lead+w, 40  );

	lead+=30; w = 0;
	w += renderIdeograph( g, blank, lead+w, 40  );
	w += renderIdeograph( g, a, lead+w, 40  );
	w += renderIdeograph( g, m2, lead+w, 40  );

	lead=0; w = 0;
	w += renderIdeograph( g, blank, lead+w, 80  );
	w += renderIdeograph( g, a, lead+w, 80  );

	lead+=30; w = 0;
	w += renderIdeograph( g, d, lead+w, 80  );
	w += renderIdeograph( g, a, lead+w, 80  );
	w += renderIdeograph( g, m2, lead+w, 80  );

	... and then this method to do the paint of each part of an ideograph: ...

	/** Doesn't really render an ideograph, renders a single glyph from the Font */
	public int renderIdeograph( Graphics g, int i, int x, int y )
	{
		char[] chars = Character.toChars( i );
		String drawString = String.copyValueOf( chars );
		int advance = g.getFontMetrics().charsWidth( chars, 0, chars.length );

		g.drawString( drawString, x, y );

		return advance;
	}
</pre>
</blockquote>
<p>Which renders exactly like this:</p>
<p><a href='http://t-machine.org/wp-content/uploads/2008/03/hangul-adam-unbatang.PNG' title='hangul-adam-unbatang.PNG'><img src='http://t-machine.org/wp-content/uploads/2008/03/hangul-adam-unbatang.PNG' alt='hangul-adam-unbatang.PNG' /></a></p>
<p>Which makes me want to point out the nice thing about properly specified fonts: in the source code, I simply did &#8220;the natural thing&#8221;, as if I were outputting characters in an arbitrary conjoined language:</p>
<ol>
<li>Render the first part of the first ideograph at (x,y)</li>
<li>Ask the font to tell you how many pixels wide (w) it just rendered that part</li>
<li>Render the next part of the first ideograph at (x+w,y)</li>
<li>&#8230;repeat until first ideograph is complete, increasing w more and more each time&#8230;</li>
<li>Choose a value for how much you want the ideographs separated from start to start (ideograph_width)</li>
<li>Render the first part of the second ideograph at (x + ideograph_width, y)</li>
<li>&#8230;repeat as for first ideograph</li>
</ol>
<p>And it worked. First time. I didn&#8217;t expect it to &#8211; I expected to have to do something strange like manually &#8220;reset&#8221; the (w) value each time I went from the first line of the ideograph to the second (Korean orders letters top-left, top-right, bottom-left, bottom-right, (repeat) &#8230; as opposed to Latin which is just left, right, more right, even more right, etc).</p>
<p>For this to have worked, it means the font is deliberately rendering the lower letters (e.g. d2 and m2 in my constants) a long way to the left of the origin that you tell it to render them at. This would be very, very confusing if you just tried to render these letters individually (well, duh).</p>
<p>Of course, if you try to run that code using Microsoft&#8217;s Arial Unicode MS font, you get a complete mess instead, because that font is FUBAR, as mentioned before. You get this:</p>
<p><a href='http://t-machine.org/wp-content/uploads/2008/03/hangul-adam-arial-unicode.PNG' title='hangul-adam-arial-unicode.PNG'><img src='http://t-machine.org/wp-content/uploads/2008/03/hangul-adam-arial-unicode.PNG' alt='hangul-adam-arial-unicode.PNG' /></a></p>
<p>&#8230;which is completely incomprehensible.</p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2008/03/28/writing-games-in-korean-part-1/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Java considered harmful as first programming language&#8230;</title>
		<link>http://t-machine.org/index.php/2008/02/13/java-considered-harmful-as-first-programming-language/</link>
		<comments>http://t-machine.org/index.php/2008/02/13/java-considered-harmful-as-first-programming-language/#comments</comments>
		<pubDate>Wed, 13 Feb 2008 17:50:54 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[java tutorials]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tmachine1.dh.bytemark.co.uk/blog/index.php/2008/02/13/java-considered-harmful-as-first-programming-language/</guid>
		<description><![CDATA[Today, I was pointed at an article suggesting that java is responsible for the decline in the quality of Computer Science graduates.
Specifically if you want to be a Computer Scientist, I’d say that the initial claim that “java is bad as a first language” is true, just as “C++ is bad as a first language” [...]]]></description>
			<content:encoded><![CDATA[<p>Today, I was pointed at an article <a href="http://www.stsc.hill.af.mil/CrossTalk/2008/01/0801DewarSchonberg.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.stsc.hill.af.mil/CrossTalk/2008/01/0801DewarSchonberg.html');">suggesting that java is responsible for the decline in the quality of Computer Science graduates</a>.</p>
<p>Specifically if you want to be a Computer Scientist, I’d say that the initial claim that “java is bad as a first language” is true, just as “C++ is bad as a first language” is true. What disappoints me is that they go on to suggest that C++ is good as a first language (disclaimer: my uni course taught ML as first language, ARM assembler as second).<br />
<span id="more-101"></span></p>
<p>Do you want to be a Computer Scientist? Why would you want that? Well, the article makes some good points in that regard &#8211; essentially, if you want to be an OK-to-good programmer, then it will help to be a CS, but not required, but if you want to be a *great* programmer, you absolutely need to be a CS. So, if you&#8217;re not interested, stop here :). But if you hope to be a really good programmer one day &#8211; or to understand those who are &#8211; read on.</p>
<h4>Objections</h4>
<p>- I could defend using a very pure, low-level assembler as first language (preferably a very modern one, with very logical syntax &#8211; ARM is the best example I know)</p>
<p>- I could defend using a very pure, low-level functional as first language (preferably one with a really good IDE and debugger, I haven’t used any recently enough to know of any with particularly good IDE’s that beginners would find easy :( )</p>
<p>- I could probably even defend using a very pure, low-level data driven language as first language (I have too little experience with data languages to make a good suggestion here), although I don’t think that would be as useful as either of the first two options.</p>
<p>But anything C-derived seems to be an excuse for avoiding teaching the fundamentals of computer science: you should either be teaching the theory (as the article laments we are not currently doing), or you should be teaching the hardware (as it also laments, but less forcefully, and seems to mention only as an excuse for why C is good). Or&#8230;you should be accepting that you’re not [even attempting to] teaching either. C/C++/Java force you to learn neither of those things, so make for poor first languages IMHO.</p>
<h4>Assembler</h4>
<p>Teaches you to be REALLY good at the meat of programming: the individual lines of code that follow one after another within any chunk of a program, such as the body of a function or method.</p>
<h4>Functional</h4>
<p>The closest form of programming to the theoretical mathematics of programming, and hence the easiest in which to achieve a lot of solutions (for instance, parallel programming such as needed to take advantage of multiple CPU&#8217;s or multiple servers in a cluster is orders of magnitude easier to do in a functional language).</p>
<h4>Data-driven</h4>
<p>Much of the programming problems in the world come down to manipulating, generating, or managing data. Data languages don&#8217;t get much attention because they aren&#8217;t general-purpose languages, but they&#8217;re the best choice for a big chunk of the systems that most programmers will spend most of their lives working with. Amongst the non-general languages, they&#8217;re probably the most useful to a modern programmer (sheer speculation on my part there &#8211; feel free to smack me down for my foolishness :)).</p>
<h4>Flamebait articles</h4>
<p>In passing, I wanted to comment on the article itself. Mainly because on the whole it&#8217;s a GOOD article, making some good points and bringing attention to some problems that have been allowed to get out of hand &#8211; but I can&#8217;t recommend it without reservations, because in some respects it&#8217;s deeply flawed. To people under-experienced in this stuff (e.g. undergraduate programmers, and high-schoolers choosing CS degrees) I think it would be easy to be misled by some stuff in the article that really isn&#8217;t fair.</p>
<p>The way the article has been written makes it easy to speed-read it and recycle it as food for a “java is bad” argument :(. As noted at the start, I think the arguments for this aspect ALL hold equally true for declaring that &#8220;C++ is bad&#8221;, but the author not only glosses over this but instead even has a half-hearted attempt to argue the opposite. To see this as justification for either argument would be foolish, of course, but it&#8217;s easy to see how pre-prejudiced (i.e. flamers and trolls ;)) people will do that. I&#8217;m sure it will happen, although I don&#8217;t think the authors meant it that way (if anything, I think it&#8217;s an extended attempt to elevate Ada in people&#8217;s estimation). In the modern internet world, on certain topics (such as anything that compares and contrasts programming language) you have a duty to be extra careful about how you present your arguments.</p>
<p>Given the way the article starts (by poking java), I&#8217;m particularly disappointed that the “Why Java matters” section misses out any of the stronger benefits of java in particular, mainly I think because they wanted to mention them in the Ada section (where several of them appear), and didn’t want the fact that they’d mentioned them in the java section to weaken the argument (I note that C#/.NET/CLR isn’t mentioned at all either &#8211; if you’re even going to try to defend java as a choice, I think you should mention other managed languages).</p>
<p>I also think it’s odd that they would choose LISP as the only functional language represented. Not just because I’m an ML fanboy :), but because IME, functional languages fit much more closely to standard human approaches to problem solving than imperative languages.. If you&#8217;re going to pick the ideal language to teach students first, it would be a functional language, so there ought if anything to be MORE fn langs than imperative ones in the list &#8211; but it&#8217;s the other way around. I think if they fairly compared both fn and imperative, the fn langs would probably win the majority of reader mindshare. I think the main reason they didn&#8217;t include them is probably their desire to make Ada seem good, as mentioned above.</p>
<p>That&#8217;s purely my personal opinion, of course; take it or leave it&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2008/02/13/java-considered-harmful-as-first-programming-language/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java NIO Server Example</title>
		<link>http://t-machine.org/index.php/2008/01/22/java-nio-server-example/</link>
		<comments>http://t-machine.org/index.php/2008/01/22/java-nio-server-example/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 10:06:59 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[java tutorials]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tmachine1.dh.bytemark.co.uk/blog/index.php/2008/01/22/java-nio-server-example/</guid>
		<description><![CDATA[I&#8217;ve made a small simple but complete java NIO server (with full source included) that is free for anyone to use for anything. At the moment, it only deals with sending and receiving strings, and isn&#8217;t optimized, but if anyone wants to improve it and send me the changes then I&#8217;ll post up an improved [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve made a small simple but complete java NIO server (with full source included) that is free for anyone to use for anything. At the moment, it only deals with sending and receiving strings, and isn&#8217;t optimized, but if anyone wants to improve it and send me the changes then I&#8217;ll post up an improved version here.</p>
<p>Download, documentation, license details, tutorial etc after the jump&#8230;</p>
<p><span id="more-92"></span></p>
<p>EDIT: I&#8217;ve now created a SourceForge project for this project &#8211; <a href="http://javanioserver.sourceforge.net/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://javanioserver.sourceforge.net/');">http://javanioserver.sourceforge.net/</a></p>
<p>EDIT2: Because Wordpress is utterly, utterly crap at allowing you to have category pages, the old &#8220;main news page&#8221; for the project no longer exists. Blame Wordpress, and hope that *one day* they will bother to fix their code so that it supports this standard blogging feature :).</p>
<h4>Download</h4>
<p>The most important thing is the full source code (DOWNLOAD FROM SOURCEFORGE LINK ABOVE), but if you decide just to use it as-is, you&#8217;ll probably want the much smaller binary-only jar (DOWNLOAD FROM SOURCEFORGE LINK ABOVE). NOTE: both jars have an auto-run that runs a very simple Hello,World! server so you can check they are working OK.</p>
<p>You&#8217;ll also need log4j (the fast, powerful, and extremely widely used open-source logging-library) &#8211; if you want the application to auto-run, you&#8217;ll need to name your log4j file &#8220;log4j-1.2.8.jar&#8221; (there&#8217;s a copy of the latest version here (DOWNLOAD FROM SOURCEFORGE LINK ABOVE), already renamed for you, that you can download directly; sorry, that was my mistake when building the JAR).</p>
<p>Finally, there are <a href="http://javanioserver.sourceforge.net/doc/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://javanioserver.sourceforge.net/doc/index.html');">fully-documented javadocs here</a> that should answer all your questions and explain how to use this library.</p>
<h4>Why did I make this?</h4>
<p>		Mainly because Sun&#8217;s NIO libraries are good, but very low-level, with a few major flaws and a few unfixed bugs,<br />
		so that it takes a lot of time and effort to make even the simplest of working<br />
		client/server applications with them. This small, simplistic library (fewer than 1000 lines of code)<br />
is designed so that you can:</p>
<ul>
<li>easily implement a new single-threaded, non-blocking NIO server in minutes
<li>edit the fully-documented source to customize it any way you need</li>
<li>read all the source code and understand how it was done so you can make your own servers from scratch</li>
</ul>
<p>		In case you weren&#8217;t aware, MOST resources on the internet providing source code<br />
		for Java NIO servers are WRONG and FULL OF BUGS that mean they WILL NOT WORK -<br />
		including BOTH of the O&#8217;Reilly books I&#8217;ve read (&#8221;Java NIO&#8221; and &#8220;Learning Java&#8221;).<br />
		That&#8217;s pretty shameful considering those are both extremely widely-used books :(.<br />
		In both cases, the authors clearly A) never read the API properly, and B) never<br />
		actually tried writing any NIO server code in their life. Or, at least, they<br />
		wrote it but never ran it on the internet &#8211; a glance at their source code shows<br />
		it won&#8217;t work except on a local switched LAN, and even then only for VERY simple<br />
		programs.</p>
<p>		So, although this library is NOT particularly optimized (mostly in that it is<br />
		wasteful with how it creates ByteBuffers), it DOES ACTUALLY WORK and is pretty<br />
		simple and well-documented, so hopefully you can use it to make your own servers.</p>
<h4>Why string-based, and TCP only?</h4>
<p>		TCP only: because I created this for &#8220;incubation&#8221; projects &#8211; i.e. small game<br />
		experiments I wanted to try out. The code supplied will actually work reasonably<br />
		well for most realtime games with current internet performance (I&#8217;ve made various<br />
		simple multiplayer games with it) &#8211; but if you find your game is particularly good<br />
		and want to make a proper multiplayer version over the internet, you&#8217;ll want to<br />
		replace the TCP with UDP. That will be very, very easy to do &#8211; but not necessary<br />
		for the majority of people who are just making simple games.</p>
<p>		String-based: because A) you ALWAYS need strings! (what, your game has no in-game<br />
		chat? Shame on you!), and B) it&#8217;s much, much easier to debug, and C) when you&#8217;re<br />
		developing code very fast (I&#8217;m using Scrum) strings allow you to use &#8220;fuzzy&#8221;<br />
		message protocols, such as XML + XPath, which means that when you switch around<br />
		features, or change the message format, most of your code carries on working fine.<br />
		Binary protocols tend to break every time you make even one tiny change.</p>
<p>		When you get to the point where strings aren&#8217;t good enough performance for your<br />
		game, you&#8217;ve already got a pretty damned advanced game, and you&#8217;ll find the only<br />
		thing you need to do to make this server work purely in bytes is to REMOVE lines<br />
		of code (all the Charset encoding and decoding) and to change one or two method<br />
		signatures to accept bytearrays or bytebuffers instead of strings as argument.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6323489610521656";
/* 468x60, created 10/12/08 */
google_ad_slot = "2776044738";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2008/01/22/java-nio-server-example/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Ten tips and tricks for writing Facebook Apps</title>
		<link>http://t-machine.org/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/</link>
		<comments>http://t-machine.org/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/#comments</comments>
		<pubDate>Fri, 21 Sep 2007 08:38:36 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[facebook]]></category>
		<category><![CDATA[java tutorials]]></category>

		<guid isPermaLink="false">http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/</guid>
		<description><![CDATA[(Only a couple of these are java-specific, but this is a.k.a.: &#8220;How to make Facebook Apps using Java &#8211; part 3&#8243;)
(I assume you&#8217;ve already had a look at part 1 and part 2? They&#8217;re more beginner-oriented)
Bugs, Misconceptions, and Subtle Features
Interfacing with Facebook&#8217;s servers is pretty hard, considering how seemingly trivial the interface is. Obviously the [...]]]></description>
			<content:encoded><![CDATA[<p>(Only a couple of these are java-specific, but this is a.k.a.: &#8220;How to make Facebook Apps using Java &#8211; part 3&#8243;)</p>
<p>(I assume you&#8217;ve already had a look at <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/');">part 1</a> and <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/');">part 2</a>? They&#8217;re more beginner-oriented)</p>
<h4>Bugs, Misconceptions, and Subtle Features</h4>
<p>Interfacing with Facebook&#8217;s servers is pretty hard, considering how seemingly trivial the interface is. Obviously the almost total lack of documentation is mostly to blame for this, but some of it is just common bugs that have yet to be fixed.</p>
<p>So, here&#8217;s ten things I&#8217;ve found whilst fiddling with the API, and some of the nicer features that may not be immediately obvious even if you do read the docs provided by FB (you should go read all of them, but &#8230; there&#8217;s some bad organization and layout, so it can be a chore reading the mega-long HTML pages, with many of the API features having just blanks for description fields :( ).</p>
<p><span id="more-43"></span></p>
<h4>#1 &#8211; FacebookRestClient.java is broken (bug)</h4>
<p>I&#8217;ve had a couple of problems with this class, provided by FB themselves, although most of them turned out to be just inconveniences / bad design. This one, however, is clearly a bug, since it&#8217;s impossible to use some of the methods in the class until you fix their source code.</p>
<p>NOTE: I&#8217;ve done this for you, at the bottom of this page is a link to download a &#8220;fixed&#8221; version of the source, along with some other useful files. What follows is FYI in case you want to make the change yourself&#8230;</p>
<p>In line 103, you need to change:</p>
<pre>
<code>
protected class Pair&lt;N, V&gt; {
</code>
</pre>
<p>to:</p>
<pre>
<code>
public class Pair&lt;N, V&gt; {
</code>
</pre>
<p>Note: without this, you cannot legally create instances of that class from within your own code.</p>
<p>If you cannot create instances of that class, you cannot provide the arguments to the handful of methods that REQUIRE a <code>Pair&lt;N,v&gt;</code> (or a list of them) as one of their arugments.</p>
<p>I&#8217;m not sure why the author of the class made this class protected &#8211; seems to just be a silly mistake. I imagine they thought that perhaps &#8220;it&#8217;s an internal hidden class &#8211; therefore I must hide it&#8221; &#8230; but it seems to exist mainly to be one of the REQUIRED arguments to the public methods, so this is obviously wrong. Oh well.</p>
<h4>#2 &#8211; Callback URL is not a page, it&#8217;s a directory</h4>
<p>This one is annoyingly subtle &#8211; everywhere you use the callback URL, and create canvas pages, this isn&#8217;t explained. When you are REQUIRED to invent a URL for this, you&#8217;re not told what it really is. Instead you have to dig into the docs to find the following nugget:</p>
<blockquote><p>
If you want to create Facebook Canvas pages, you must specify a directory name for your pages. Directory names are unique so you cannot have a name another app has claimed. Once you specify a directory name, going to http://apps.facebook.com/YOUR_DIRECTORY_NAME/pagex.abc will render pagex.abc from <YOUR CALLBACK URL>pagex.abc in the Facebook Canvas.
</p></blockquote>
<p>Note: that is CORRECT even though it appears to have a typo &#8211; Facebook really does render the page <YOUR CALLBACK>pagex.abc with no slash inserted between the two parts &#8211; if you don&#8217;t put a slash on the end of your Callback URL when you type it into the Create Application form, you&#8217;ll find there&#8217;s no slash between the Callback URL and the &#8220;pagex.abc&#8221;.</p>
<p>Note2: You can, in fact, deliberately request &#8220;http://apps.facebook.com/YOUR_DIRECTORY_NAME//pagex.abc&#8221; (note the double-slash) to cause FB to insert a slash in the request it sends to your webserver. But I woudl advise against this &#8211; it&#8217;s the kind of behaviour that&#8217;s likely to be removed in the future, since double-slashes are not legal in URL&#8217;s IIRC (c.f. the URL/URI RFC&#8217;s if you&#8217;re interested&#8230;), and are usually a sign of attempts to hack a server (so are strongly discouraged).</p>
<p>I&#8217;d actually given up on creating canvas pages, and had just moved to doing everything with relative iframe links. This is, apparently, WRONG (and probably explains some of the other inconveniences I&#8217;ve had to date).</p>
<p>So, to be entirely clear, here&#8217;s the way you should make your Canvas pages (I think!)</p>
<ol>
<li>When you choose a Callback URL, make sure you type it in with a slash on the end</li>
<li>Each page you want as part of your app you should link to as &#8220;[callback URL]/[page name]&#8220;</li>
<li>In J2EE, map a servlet (in the simplest case; get more fancy if you prefer using struts etc) onto the directory path</li>
<li>Configure that servlet to handle authentication (see my previous post on <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/');">how to do facebook authentication</a>)</li>
<li>&#8230;and to chain the request to a different servlet by reading the &#8220;[page name]&#8221; part of the incoming URL</li>
</ol>
<p>NB: there are various ways of doing that more elegantly in J2EE. I don&#8217;t want to start writing a tutorial on J2EE, so I&#8217;m not going to go into them &#8211; there&#8217;s tonnes and tonnes of info and docs on this stuff if you don&#8217;t know it yet &#8230; google is your friend!</p>
<h4>#3 &#8211; Facebook apps can ONLY change things when one of their users is in the middle of using Facebook</h4>
<p>You CANNOT perform actions with the FB API unless at least one of your app&#8217;s users is actively logged in to Facebook AND is using your application.</p>
<p>This is by design, but it has some nasty knock-on effects. Essentially, it seriously limits your ability to interface FB with other applications and networks, because although FB users can have arbitrary effects on external data, external data is forcibly prevented from having any effect on FB.</p>
<p>Example? Well, you can only post to the newsfeed of user X if user X themself is currently using FB *right now* at the moment you want to do the post. That means that you cannot, say, post to someone&#8217;s newsfeed (and by extension to all their Friends&#8217; feeds for free) each time &#8220;someone visits my MySpace page&#8221; or each time &#8220;someone rates me a 10 on HotOrNot&#8221;.</p>
<p>There are workarounds:</p>
<p>Workaround 1: many of the API actions can legally be peformed for ANY of the &#8220;users of your application&#8221; if &#8220;any&#8221; of the other users are actively logged-in. For instance, you can query the friends of one of your users so long as at least one user is logged-in. Assuming your app is popular, there will always be SOMEONE logged-in, and you can piggyback of that logged-in user to refresh other data inside your app that depends upon reading info from facebook.</p>
<p>Workaround 2: In particular, anywhere that you use FBML, you can insert an <fb:ref> tag, and for a given fb:ref it is possible &#8211; with a single method call &#8211; to simultaneously update ALL Facebook pages (every user profile, for instance) that has the fb:ref tag in it.</p>
<p>The way the tag works is that you include something like this:</p>
<pre>
<code>
&lt;fb:ref url="http://yoursite/facebook/profile-FBML" /&gt;
</code>
</pre>
<p>inside the FBML you &#8220;set&#8221; as each user&#8217;s profile-FBML for your app.</p>
<p>Sometime later, perhaps once every hour &#8211; and only when you have a logged-in user who&#8217;s Facebook authToken you&#8217;re using! &#8211; you call:</p>
<pre>
<code>
// See item #10 on this page for more info!
iFacebookClient.fbml_refreshRefUrl( "http://yoursite/facebook/profile-FBML" )
</code>
</pre>
<p>&#8230;and ALL the user profiles will update simultaneously. Allegedly &#8211; I haven&#8217;t tried this yet myself, I&#8217;m only using FBML a very small amount at the moment. I&#8217;ll update this as and when I have problems / find solutions / etc :).</p>
<p>NB: this ONLY allows you to update the &#8220;common&#8221; or shared parts of people&#8217;s profiles (or whatever FBML you&#8217;re setting) &#8211; it doesn&#8217;t allow you to update customized FBML for each person.</p>
<p>i.e. you could use it to have a &#8220;top 10 leaderboard of all users&#8221; that appers in everyone&#8217;s profile and updates frequently seemingly automatically, but you could NOT use it to have a &#8220;your position on the leaderboard&#8221; that updates automatically (you would only be able to update that part for each user when that particular user simultaneously logged-in to your app and to facebook).</p>
<p>However &#8230; you can still use workaround #1 to update EVERYONE&#8217;s profiles manually, one-by-one, whenever ANYONE is logged-in, because the method call to update an individual profile has an optional argument that lets you specify exactly which profile to update &#8211; it doesn&#8217;t HAVE to update only the profile of the logged-in user.</p>
<h4>#4 &#8211; Javascript is not allowed in FBML</h4>
<blockquote><p>
Currently, Javascript is not allowed. If you include attributes like onClick, onMouseOver, onKeyUp, etc. we will strip them out.
</p></blockquote>
<p>So, in case you were wondering, *that&#8217;s* why your javascript ain&#8217;t working&#8230;</p>
<h4>#5 &#8211; CSS is not allowed in FBML (with exceptions)</h4>
<p>Referencing external CSS stylesheets is not allowed, but you can use style tags and put your CSS definitions there.</p>
<p>I *think* that&#8217;s another typo (argh!) &#8211; I think they meant &#8220;but you can use style ATTRIBUTES&#8221; (i.e. the person writing it didn&#8217;t realise that style=&#8221;" is an HTML attribute, whereas HTML tags look like this: <code>&lt;span&gt;&lt;/span&gt;</code>).</p>
<p>i.e. you are NOT allowed to do this:</p>
<pre>
<code>
&lt;head&gt;
&lt; ... stylesheet href="..."&gt;
</code>
</pre>
<p>(you&#8217;re pointing to the stylesheet on some other website (even your own website) on the internet, using the URL of the stylesheet to tell HTML to pull it in)</p>
<p>&#8230;but you ARE allowed to do this:</p>
<pre>
<code>
&lt;span style="border-top: 30px; margin-right: 0; text: #ff0000;"&gt;
some formatted text
&lt;/span&gt;
</code>
</pre>
<p>So, you&#8217;re allowed to &#8220;use&#8221; CSS within the HTML, but you just aren&#8217;t allowed to make your HTML clean, readable, easy to edit, or easy to debug. That sucks. Most people who use CSS will avoid doing &#8220;CSS in style attributes&#8221; like the plague &#8211; it&#8217;s messy and horrible and really hard to maintain.</p>
<p>But at least you can actually use CSS, instead of being forced to write 10-years-old HTML from the pre-CSS days.</p>
<h4>#6 &#8211; The Create-App HTML form (bug)</h4>
<p>The create-app page on FB is broken &#8211; it periodically saves its data to the live servers, but the data it displays that it THINKS it has saved is not the same as what has ACTUALLY been saved. If you change e.g. your Callback URL, it will APPEAR to change on the settings, but it won&#8217;t have changed in real life, but then if you refresh the settings it will APPEAR to have reverted to the old value, but if you &#8220;edit&#8221; it using the link provided, the value in the textbox will be the NEW value (that it has just claimed it is NOT using).<br />
This is very confusing, and a silly bug, but what it means is: when you change your callback URL, just keep trying refresh on your canvas page URL (apps.fb.com/yourapp) until it finally &#8220;works&#8221;. Some people have had to wait hours for this to happen, others waited minutes. I found it took around an hour to update.</p>
<p>Also &#8230; that whole page is a nightmare. It&#8217;s badly explained, it has far too much text, and critically important concepts (like your Callback URL, which is almost the only thing on the whole page you have to fill out, but which &#8211; contrary to the instructions! &#8211; you HAVE to fill out) are buried deep within it. c.f. Item number 2 above for more info just on the Callback URL alone, info which SHOULD have been embedded in this form.</p>
<h4>#7 &#8211; Fancy GUI hide/show effects for free</h4>
<blockquote><p>
Adding the attributes clicktohide and clicktoshow, you can dynamically hide and show content rendered with FBML
</p></blockquote>
<p>FB even give an example (how nice of them):</p>
<pre>
<code>
&lt;span id="cdc03" style="background: yellow"&gt;this can appear and disappear&lt;/span&gt;
&lt;input type="submit" clicktohide="cdc03" value="hide"/&gt;
&lt;input type="submit" clicktoshow="cdc03" value="show"/&gt;
</code>
</pre>
<h4>#8, #9, and #10 &#8211; FacebookRestClient.java is very bad java (bug)</h4>
<p>Actually, I got fed up with this crappy class. Problems include:</p>
<ol>
<li>It&#8217;s not an interface</li>
<li>It&#8217;s got bugs (c.f. the Pair inner class bug above)</li>
<li>Many methods are 100% undocumented</li>
<li>The class itself is 100% undocumented</li>
<li>Some of the undocumented methods have undocumented REQUIRED ways to call them</li>
</ol>
<p>So &#8230; I took their source code and refactored it.</p>
<ol>
<li>Get the <a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/09/ifacebookclient.java' title='Facebook client interface'>new interface here</a> (compile all your code against the interface &#8211; anything less is just Bad Java Coding)</li>
<li>Get the <a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/09/officialfacebookclient.java' title='Bugfixed Facebook client'>new &#8220;main implementation&#8221; here</a> (this is almost 100% the original official FB source code, just refactored a little to fix some nasty design flaws in their use of conflicting method signatures)</li>
<li>Get the <a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/09/pair.java' title='Bugfixed Facebook Pair inner-class'>new &#8220;Pair&#8221; class here</a> (used to be contained within the old class with incorrect signature (see the bug above about this), now refactored into separate source file)</li>
</ol>
<h4>Epilogue&#8230;</h4>
<p>I hope these prove useful to you. If you have any problems, or want more tips on using Facebook, feel free to leave a comment. This is the third post I&#8217;ve done on how to write facebook apps, and I&#8217;ve got at least one more I want to do yet. If you want to keep up to date with these, <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/category/facebook/rss" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/category/facebook/rss');">add the &#8220;facebook&#8221; category on this blog to your RSS reader</a> (see also <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/');">part 1</a> and <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/');">part 2</a>)&#8230;</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6323489610521656";
/* 468x60, created 10/12/08 */
google_ad_slot = "2776044738";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>How to Make Facebook Apps Using Java &#8211; part 2</title>
		<link>http://t-machine.org/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/</link>
		<comments>http://t-machine.org/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/#comments</comments>
		<pubDate>Mon, 13 Aug 2007 18:28:30 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[facebook]]></category>
		<category><![CDATA[java tutorials]]></category>

		<guid isPermaLink="false">http://tmachine1.dh.bytemark.co.uk/blog/?p=20</guid>
		<description><![CDATA[In the first part, I covered a very high-level, idiot-guide to getting started with writing a Facebook app in java. This part will cover the details of how to architect your own code for basic Facebook authentication, and include code samples you can use to get up and running more quickly. It will also explain [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/');">the first part</a>, I covered a very high-level, idiot-guide to getting started with writing a Facebook app in java. This part will cover the details of how to architect your own code for basic Facebook authentication, and include code samples you can use to get up and running more quickly. It will also explain in more detail precisely how Facebook&#8217;s servers interact with your code, and what you can expect (and what their servers expect of you!).</p>
<p>NB: if the quoted source code is unreadable because it disappears off the edge of the screen, select it and copy/paste (or view source of the page to see it). The most useful stuff is put together into one class you can download here &#8211; <a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/08/facebookloginservlet.java' title='FacebookLoginServlet.java'>source code for FacebookLoginServlet.java</a>.<br />
<span id="more-20"></span></p>
<h4>iFrames vs FBML</h4>
<p>Facebook apps can be implemented one of two ways, iframes, or FBML.</p>
<table border="1">
<tr>
<th>iFrame</th>
<th>FBML</th>
</tr>
<tr>
<td>Standard part of HTML, embeds one webpage inside another</td>
<td>Proprietary Facebook programming language, very similar to HTML</td>
</tr>
<tr>
<td>You can view pages through a normal web-browser to test them</td>
<td>You cannot view anything except by running it live on Facebook</td>
</tr>
<tr>
<td>Every Facebook page view goes via your webserver, so you can debug problems</td>
<td>All requests are internal on the Facebook servers, you cannot find ANY information if something goes wrong</td>
</tr>
<tr>
<td>Requires you to provide your own webserver</td>
<td>Can run without an external webserver ***</td>
</tr>
</table>
<p>*** &#8211; NB: actually, the way Facebook have designed their system, you need your own webserver anyway, they won&#8217;t let you make a Facebook App without one. So, although in theory FBML would be a faster and simpler way to get a basic app up and running, in practice, it doesn&#8217;t save you any time or effort at all.</p>
<p>Mostly, I&#8217;ll be assuming you want to write your app using iframes instead of FBML. FBML is great, and for some parts of your app you will want to use it, but the fact you can&#8217;t debug it makes life extremely difficult. If you can get all your code working with iframes first, then it will be relatively easy to switch some bits to FBML when the time comes. It&#8217;s much harder to try things the other way around.</p>
<h4>Facebook Apps: Detailed explanation</h4>
<p>What happens when a Facebook user tries to use your Facebook App?</p>
<ol>
<li>User opens their web browser</li>
<li>Finds a link to your app &#8211; usually your Canvas Page URL (http://apps.facebook.com/[your app name])</li>
<li>Clicks on the link</li>
<li>Web browser goes to that site (part of FB) and asks for the webpage</li>
<li>Facebook sends back the Facebook navbar, with an empty iframe in the centre</li>
<li>Facebook redirects the browser to your site to get the contents of the iframe &#8211; AND adds extra information to the request from the user</li>
<li>Web browser automatically goes to YOUR site, sending the extra information FB provided it</li>
<li>Your site creates a webpage, and sends it to the user&#8217;s browser</li>
<li>User&#8217;s browser renders your webpage inside the iframe embedded inside the page it got from FB</li>
</ol>
<p>&#8230;but what does this look like to the user?</p>
<ol>
<li>User opens browser</li>
<li>Clicks on the name of your app</li>
<li>Your app appears on the screen inside the navbars etc for Facebook</li>
</ol>
<p>So, the first thing to understand, especially if you&#8217;ve used FB a lot yourself, is that there&#8217;s a lot more going on behind the scenes than appears to the user. This will become especially clear when you make a mistake and start trying to debug your app.</p>
<h4>Authentication</h4>
<p>There are two &#8220;modes&#8221; in which you can create a webpage to display as part of your app:</p>
<ul>
<li> Default</li>
<li> Authenticated</li>
</ul>
<p>In the default mode, i.e. if you do nothing special, you have NO ACCESS to any of Facebook&#8217;s data. You cannot find out ANYTHING about the Facebook user &#8211; you can&#8217;t find their name, you can&#8217;t find their friends, you can&#8217;t post items on their Wall, nothing.</p>
<p>In the authenticated mode, you have full access to:</p>
<ul>
<li> read all the data of the currently logged-in user</li>
<li> most of the data of all OTHER users of your app (people who have &#8220;added&#8221; your app to their Facebook account)</li>
<li> send messages, post newsitems, etc, from the logged-in user (but they have to OK this manually)</li>
</ul>
<h4>Authenticating in java</h4>
<p>FB provides you with a java class, <code>FacebookRestClient.java</code>, which you can use to authenticate with the FB servers. Once you have authenticated an instance of this class, that class will then ALSO provide you with access to all the features of Facebook (reading data about users, sending messages to other users, etc).</p>
<p>FB has partially documented the way that authentication works, but there are lots of missing details. In particular, there is no documentation on how to use the <code>FacebookRestClient</code> class to do authentication, and several of the methods that appear to work together are actually mutually exclusive. This is because that one class is responsible both for doing Web-based apps (the only kind of app that most people have ever seen or used on Facebook) and Desktop apps (which do exist but are much less common right now).</p>
<p>In brief, you need to:</p>
<ol>
<li>Generate a URL for a custom login page for your app (http://www.facebook.com/login.php?api_key=[your api key goes here] )</li>
<li>Send a redirect to the user&#8217;s web browser to force them to go to that page</li>
<li>&#8230;Facebook will then redirect them back to your &#8220;Callback URL&#8221; page&#8230;</li>
<li>Read the &#8220;auth_token&#8221; parameter from the HTTP Query String</li>
<li>Instantiate an instance of <code>FacebookRestClient</code> using your API key and your API secret</li>
<li>Invoke <code>.auth_getSession( auth_token )</code> using the value of auth_token you received</li>
</ol>
<h4>Authenticating your servlets</h4>
<p>Now, you may notice a problem with the above sequence of events. Traditionally, when writing a J2EE app, you have multiple servlets, one for each &#8220;page&#8221; of your website &#8211; but in order to authenticate, the servlet MUST redirect the user back to Facebook, which will then ALWAYS send the user back to your Callback URL page, which means they will be sent to the &#8220;wrong&#8221; page.</p>
<p>Note: just because you redirect the user to Facebook&#8217;s login page doesn&#8217;t actually mean the user SEES a login page &#8211; if they are already logged-in to Facebook, FB just automatically sends them straight back to your site (but this time, it gives your site the login information, which doesn&#8217;t otherwise do!)</p>
<p>So, effectively, Facebook ONLY ALLOWS ONE SERVLET to authenticate with Facebook &#8211; whichever servlet you gave the address of when you filled in the &#8220;Callback URL&#8221; field when creating your app on Facebook&#8217;s Developer page.</p>
<p>That&#8217;s not a big problem, though. J2EE servlets have the Session object, automatically maintained by your J2EE container, that will take care of this: if you ever want the user to be authenticated when using your app, just make the Callback URL page force the user to login once (as noted above, if already logged in to FB, the user won&#8217;t be asked to login again, but you still have to force FB to make the check), and then store the authenticated instance of <code>FacebookRestClient.java</code> in the J2EE Session object, like this:</p>
<p><code></p>
<pre>protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
   ...
   FacebookRestClient authenticatedClient = new FacebookRestClient( apiKey, secret );
   authenticatedClient.setIsDesktop(false);
   request.getSession().setAttribute( "auth", authenticatedClient );
}
</pre>
<p></code><br />
Then, whenever you need to interrogate Facebook about any data in ANY of your servlets, fetch the authenticated <code>FacebookRestClient</code> instance from the J2EE session, and use it directly:<br />
<code></p>
<pre>
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
   FacebookRestClient authenticatedClient = (FacebookRestClient) request.getSession().getAttribute( "auth" );
   ...
}
</pre>
<p></code><br />
In fact, I&#8217;d advise you to dedicate one servlet purely to logging-in to Facebook, and make that servlet your Callback URL one. For instance, here&#8217;s <a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/08/facebookloginservlet.java' title='FacebookLoginServlet.java'>source code for FacebookLoginServlet.java</a> you could use directly for that servlet. Note that the provided source code assumes you are using Apache Log4j to do your logging &#8211; you may want to change that to use Sun&#8217;s java.util.logging API. I advise you at least use some form of logging (it helps a lot when debugging!)</p>
<h4>Old sessions</h4>
<p>You also have to handle the situation where a player leaves their web browser open for a long time, long enough that the J2EE Session timesout and/or the Facebook authentication timesout, and then they hit &#8220;refresh&#8221;. If you&#8217;re merely starting every doGet / doPost method in your servlets with the <code>request.getSession()</code> call above, you&#8217;ll find that either the Session is empty and you get a null client, or you get a client but that when you attempt to invoke methods on it they all fail with <code>FacebookException</code>&#8217;s. Exactly what will go wrong depends upon the implementation of your J2EE container, and how long it keeps Sessions alive for before expiring them (and whether the connected web browser kept all the Cookie&#8217;s it was given).</p>
<p>For this, I currently just surround all my doGet&#8217;s with a big try/catch:<br />
<code></p>
<pre>
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
   try
   {
      ...
   }
   catch( FacebookException e )
   {
      logger.error( "Facebook exception, probably due to timeout on authentication; sending error page to user", e );
      String loginPage = "http://www.facebook.com/login.php?api_key="+apiKey+"&amp;v=1.0";
      response.getWriter().println( "&lt;h1&gt;Error: Couldn't talk to Facebook&lt;/h1&gt;" );
      response.getWriter().println( "Your Facebook session has probably timed out" );
      response.getWriter().println( "Please &lt;a ref=\""+loginPage+"\"&gt;click here&lt;/a&gt; to login again");
   }
}
</pre>
<p></code></p>
<h4>Testing&#8230;</h4>
<p>And, again, time to finish off with some basic tests, so you can be sure all this stuff above is working. For my basic testing, I created a servlet that would fetch the user-id of the currently-logged-in Facebook user, and ask Facebook for a list of all their friends&#8217; names. This is the same basic test that Facebook uses in their one and only piece of sample java code in their API.<br />
<code></p>
<pre>public class TestFaceBookServlet extends HttpServlet
{
   protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException, FacebookException
   {
      FacebookRestClient client = (FacebookRestClient) request.getSession().getAttribute("facebookClient");
      client.setDebug(true);

      logger.info( "Fetching friends for user to prove that our auth to FB's server worked OK ... should see a list of \"uid\"s now, with NO java-exceptions!");
      Document d = client.friends_get();

      FacebookRestClient.printDom(d, "  ");
   }
}
</pre>
<p></code></p>
<h4>Conclusion</h4>
<p>By now you should have:</p>
<ul>
<li> A facebook app that you can connect to via Facebook itself that displays the content from your basic servlets</li>
<li> A login-servlet as your Callback URL that automatically logs in the current user to Facebook</li>
<li> A simple test servlet that your login-servlet redirects to after a successful login, and which prints in your server log-files a list of all the uid&#8217;s of your friends</li>
</ul>
<p>In the next part, I&#8217;ll probably stop to cover likely problems and gotchas you&#8217;ll run into, since there&#8217;s quite a few you&#8217;re likely to hit by this point.</p>
<p>If there&#8217;s anything else you&#8217;d like to see covered, add a comment at the bottom and I&#8217;ll try to fit it in as well.</p>
<p>UPDATE 21st Sept 2007: <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/09/21/ten-tips-and-tricks-for-writing-facebook-apps/');">Third part now posted</a></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6323489610521656";
/* 468x60, created 10/12/08 */
google_ad_slot = "2776044738";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>How to Make Facebook Apps Using Java &#8211; part 1</title>
		<link>http://t-machine.org/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/</link>
		<comments>http://t-machine.org/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/#comments</comments>
		<pubDate>Thu, 02 Aug 2007 18:11:55 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[facebook]]></category>
		<category><![CDATA[java tutorials]]></category>

		<guid isPermaLink="false">http://tmachine1.dh.bytemark.co.uk/blog/?p=16</guid>
		<description><![CDATA[I wrote a game last weekend, for Facebook. Writing the entire multiplayer persistent game took a day and a half; getting it to integrate with Facebook is taking several days. Mostly, the problem is that Facebook hasn&#8217;t &#8211; yet &#8211; provided user-guide documentation, and there are plenty of bugs in their system. Without docs, you [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote a game last weekend, for Facebook. Writing the entire multiplayer persistent game took a day and a half; getting it to integrate with Facebook is taking several days. Mostly, the problem is that Facebook hasn&#8217;t &#8211; yet &#8211; provided user-guide documentation, and there are plenty of bugs in their system. Without docs, you have to guess whether a &#8220;nothing happens&#8221; is due to your mistaken guesswork, a bug in FB, or &#8230; a bug in your own code. That&#8217;s fine, but it takes time, lots of time.</p>
<p>Google kept giving me zero hits for any of the problems, or even any java-focussed docs (just one link to a FAQ on an issue that seems to be a bug that was fixed a while ago. That&#8217;s all). So, as I solve the various problems that come up, I&#8217;m writing about them.</p>
<h4>Platform</h4>
<p>First thing to be clear about: if you want to write FB apps using java, you&#8217;ll be using Enterprise Edition (J2EE). The way FB works *requires* you to provide a webserver for your app. Whilst its true that java can run in the web browser, that&#8217;s a completely different way of using java &#8211; for this, you&#8217;re going to have to find a server, and install J2EE (it&#8217;s the same as standard java, just has lots of extra libraries, only a few of which you&#8217;ll need to use).</p>
<h4>Facebook Apps: how they work</h4>
<p>This diagram shows a very simplistic summary of the different URL&#8217;s you are asked for when registering a Facebook application, or are used when serving an App. Note that FBML is served entirely internally in the FB server, it does NOT make a request to your web server.</p>
<p>NB: this image got deleted in the server crash last month; WordPress is rather badly designed with images, and doesnt save them. But it&#8217;s been stolen and copied widely all over the web, so you can probably find it relatively easily<br />
<a href='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/08/facebook-java-diagram-1.png' title='Basic explanation of facebook servers'><img src='http://tmachine1.dh.bytemark.co.uk/blog/wp-content/uploads/2007/08/facebook-java-diagram-1.png' alt='Basic explanation of facebook servers' /></a></p>
<h4>First step: Registering your Facebook Application</h4>
<p>Assuming you can find yourself a webserver/J2EE server to run your app on, and have a domain name for it (or the hosting provider gives you a default domain-name &#8211; you don&#8217;t HAVE to buy one just for your app), the first thing to do is register the app with Facebook. This just reserves the name of your app, and gets you the login details you&#8217;ll need before you can do ANY testing or development.</p>
<p>This process is <a href="http://developers.facebook.com/step_by_step.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://developers.facebook.com/step_by_step.php');">actually nicely documented</a> (and is also very simple &#8211; although the huge scary forms they ask you to fill in are very poorly explained, there&#8217;s a only a few fields you actually *need* to fill in). Don&#8217;t follow the list of things on that page literally, see the differences below that you want to make.</p>
<p>For the URL&#8217;s you need to fill-in, you&#8217;ll be making a servlet for each. So, work out the URL for each of the servlets (depends on how you setup your J2EE server), and have them ready to give to FB.</p>
<p>So, to summarise:</p>
<ol>
<li>Create a Facebook account if you don&#8217;t have one, and login</li>
<li>Add the &#8220;Developer&#8221; app to your account (link is <a href="http://developers.facebook.com/get_started.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://developers.facebook.com/get_started.php');">here</a>)</li>
<li>Go to your Home page on FB</li>
<li>Click on the Developer app in the sidebar to go to the main centre for all your Developer activity</li>
<li>Make a new application, and fill in the form it presents you with (make sure you do at least:
<ol>
<li>App name</li>
<li>Callback URL (see <a href="http://developers.facebook.com/step_by_step.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://developers.facebook.com/step_by_step.php');">the example app</a>)</li>
<li>Canvas page (see <a href="http://developers.facebook.com/step_by_step.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://developers.facebook.com/step_by_step.php');">the example app</a>)</li>
<li>iFrame (not FBML)</li>
<li>Post-add URL (see <a href="http://developers.facebook.com/step_by_step.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://developers.facebook.com/step_by_step.php');">the example app</a>)</li>
</ol>
</li>
<li>Save the api-key and the session-key that it now displays for the newly-created app &#8211; you&#8217;ll need them to do any coding</li>
</ol>
<h4>First test: Can Facebook display your Application?</h4>
<p>Create the various servlets on your server (callback, postadd, and canvas) and make each of them return basic HTML that just says &#8220;callback servlet&#8221;, &#8220;postadd servlet&#8221;, or &#8220;canvas servlet&#8221;).</p>
<p>Open a new browser window, and type in the canvas page URL from FB, something like: http://apps.facebook.com/yourApplicationName</p>
<p>You might be asked some security stuff by FB, but once you&#8217;ve got past that you should then see a Facebook page with the navbars etc, but just a big empty space in the middle with the test &#8220;callback servlet&#8221;. If so, congratulations, you&#8217;ve got your app basically working. Now comes all the hard stuff&#8230;</p>
<p>If not, first check that your servlet is even working, by copy/pasting the callback URL from your FB application setttings (click Edit Settings to re-load the form you submitted) into a browser window, and seeing if you can get the page. You&#8217;ve probably got a typo in the URL you gave FB. If the &#8220;callback servlet&#8221; text doesn&#8217;t come up on its own, without all the FB stuff, then your J2EE server is misconfigured or broken. Time for you to go find some Tomcat / jBoss / etc tutorials and get your J2EE working&#8230;</p>
<h4>Part two&#8230;</h4>
<p>Now you can move on to <a href="http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://tmachine1.dh.bytemark.co.uk/blog/index.php/2007/08/13/how-to-make-facebook-apps-using-java-part-2/');">part 2</a> of this series, covering the details of how to authenticate with Facebook and start doing interesting work, including sample source code.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6323489610521656";
/* 468x60, created 10/12/08 */
google_ad_slot = "2776044738";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://t-machine.org/index.php/2007/08/02/how-to-make-facebook-apps-using-java-part-1/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
