Blogs

Java Wish List

Tagged:  

After reading Alex Miller's predictions for what features will make it into Java 7, I couldn't help but think of my own wish list of improvements to Java (version 7 and beyond). These range from weigh-ins on the major topics of the day to minor improvements in Java's usability. Drum roll please...

1. Reification of generics. Yes, I am beating a dead horse here (it's easier when they don't talk back), but erasure sucks. Unfortunately, I think Alex is probably right when he states that reification of generics won't make it into Java 7, which means it probably won't go into any future version of Java either. Neal Gafter's explanation probably best sums it up as to why reification cannot happen while preserving compatibility. What to do? C# took the better approach to introducing generics: introduce new reified generic classes while deprecating the older non-generic ones. It is probably too late for Java to take the same approach. Quite frankly, I think that the compatibility requirement for generics in Java is far too stringent. Yes, compatibility is important, but not at the cost of the integrity of the language. Can't we admit we made a mistake and change this?

2. Improve generics verbosity. The introduction of generic type parameters, especially bounded types, makes type definitions horribly verbose. Take a look at the following example:

Map<? extends Node, ? extends Collection> map = ...;

Ouch. It would be nicer if the programmer could express bounded types in a more concise way. This might be, to borrow from C# or Scala, the use of a colon (:) to replace the extends keyword (super could use a double-colon, ::). We can now write,

Map<?:Node, ?:Collection> map = ...;

which is much better (or at least as good as it can get).

3. A more intuitive (and explicit) syntax for returns in BGGA closures. Yes, BGGA hasn't made it into the Java language (yet), but the political momentum seems to be in its favor. I dislike the use of return to mean "return from the enclosing method", as well as the use of no-semicolon expressions as kind of implicit returns. While the introduction of pure expressions may be more consistent at the compiler level (language grammar), at the syntax level it's awkward, potentially confusing, and inconsistent with Java's existing control contructs. Use of a statement form for non-local and local returns (e.g. return super and return) would be much more intuitive, though explicit non-local return syntax would be unusable outside of a closure (which complicates the life of the compiler programmer, but better him than the hordes of junior Java programmers). I'm not sure I grok Neal Gafter's explanation of why use of an expression (sans semicolon)--which is already illegal in normal Java syntax and has no meaning outside of a closure--is better than an explicit return statement. Java already has rules as to where certain keywords can be used, and the creation of closure constructs will mandate special syntax anyway.

IMHO, the simplicity of reading and writing a language trumps other concerns by a wide margin; in this view, syntactical consistency is paramount. BGGA in its current form doesn't meet this criteria. Perhaps it would just be easier if non-local returns were disallowed entirely...? I'd like to see a compelling use case for including them, at the very least.

4. Single, unified deployment mechanism for Java programs/libraries. Java has EARs, WARs, JARs, and so on. Some projects/products even include their own (e.g., SARs and MARs in Axis 2.0). It would be really nice to have a single packaging mechanism for deploying all Java programs, with appropriate variations for web applications, services, etc. Though Java modules are only intended to replace JARs, what I'd like to see is some final (and more comprehensive) form of JSR-277 (or JSR-277 integrated with OSGi) eventually replace all existing packaging formats.

5. Convention over configuration. In addition to a unified deployment mechanism, it would be nice if Java stole a few good ideas from Ruby on Rails (RoR). One of these ideas is "convention over configuration", a term coined to express the idea that one should only have to configure something if it deviates from a simple, well-defined convention. Java already has a nice example of this called the JavaBeans API. This approach could be extended to other areas of Java, especially in the way that deployment archives locate and handle various metadata files: XML Schema, WSDL, properties files, etc. There are some existing conventions regarding metadata files in Java, but they are scattered across different specifications and (in some cases) not consistently adhered to; centralization of these conventions in a specification like JSR-277 would be a good thing, as would some automatic mechanism for discovering these files without the need for system properties or other configuration.

Well, that concludes the Java Wish List, for now at least. Feel free to add your own ideas to the mix in the comments or even dispute (!) mine. Remember, not all good ideas in the Java world need to be in the form of a JSR with the attendant expert group. Let your voice be heard.

Creating a Simple JavaScript Game Board

Over at the Web Cash blog they have posted two tutorials on Game development in JavaScript, Ajax and PHP. The first tutorial explains the concept and describes how to make a game board.

Below is an excerpt from the first tutorial.

Game Development with JS, AJAX, and PHP

How can we use JS and PHP - connected through AJAX - to develop an online game?

Javascript’s main use for us is to create an interface for the game. Through Javascript we can capture user input - i.e. mouse clicks and text. We can also alter the game’s output - changing the HTML of the page, adding images, and moving things around. Javascript will provide a lot of the front end work.

PHP, on the other hand, is a more robust language for dealing with the logic of the game. PHP could be useful for developing an AI and evaluating winning conditions. It also offers a great way to store information for later use through flat files or database integration.

If we’re going to use both Javascript and PHP, we’ll need to use AJAX. This is the glue that holds the whole thing together. It will send input from the main Javascript to the PHP processing scripts. The PHP script will then send info back to the Javascript and it will alter the page’s layout accordingly.

Read the full first tutorial here.

The second tutorial goes into more detail as to how you would start creating a simple game. By the end of the tutorial you have a complete simple tic-tac-toe game (the game needs more logic added to be finished, but the concept is there).

Below is an excerpt from the second tutorial.

Creating Graphics

Tic Tac Toe Circle ImageI created two images in Inkscape to use for this board. Each is a 50×50 png file - with a gray background and a black border. The actual token (the circle or cross) is red and laid on top of the gray background.

Tic Tac Toe Cross ImageI’m no great artist, but these should work for a functional demo. We can worry about making nice circle and cross tokens later. I think getting the game working is more important than making it pretty from the get-go.

Turning Our .js Script into a Class

In making this a functional board, I also converted the script into an actual class. The script may end up being somewhat large and unwieldy - and an object oriented approach may help us keep it tidy and clean. Or it may add a lot of overhead… but I like objects.

In our HTML file, we’ll create the object like this.

<script type="text/javascript">
var tictactoe = new game();
</script>

In the attached .js file, we actually define the game object. Here’s part of the object definition.

function game() {
  //  Array to hold the bgImgs
  this.bgImgs = new Array();
    this.bgImgs[0] = 'tttcircle.png';
    this.bgImgs[1] = 'tttcross.png';

 
  //  Player information			
  this.currentPlayer = 0;
  this.players = new Array();
    this.players[0] = "Player One";
    this.players[1] = "Player Two";

 
   return true;

This class constructor does some of the initialization for us.

First, it creates an array with background images. At the moment we’re only using two images. However, this technique would be useful if you had a more complex map - with 10-15 images you could lay over a div.

Second, we create some player information variables. The ‘currentPlayer’ property is going to track whether the ‘cross’ or ‘circle’ player is currently taking a turn. The ‘players’ array will just hold the names of those players for now.

The Background Image Changing Function

One of the major methods of this class will be changeBackground(). Just like in the previous example, this method will change the background style of a given div tag. This way we can change it from an open square to a circle or cross token.

  this.changeBackground = function (boxId) {
    var box = document.getElementById('box-' + boxId);
    box.style.background = 'transparent url(' + 
      this.bgImgs[this.currentPlayer] + ') top left no-repeat';

 
    box.removeAttribute('onClick');
 
    this.changePlayer();
  }

This should be pretty straightforward. We’re storing the ‘div’ element in the ‘box’ variable. We’re then setting the ‘background’ style as we would in a css style. Remember that we stored the background images in an array (this.bgImgs) and this.currentPlayer corresponds to a key in the this.bgImgs array (either 0 or 1).

The ‘box.removeAttribute()’ method is removing ‘onClick’ from that div. We can’t use a square a second time, so we might as well eliminate the onClick handler altogether.

Finally, this.changePlayer() is calling a new method. This is going to help us switch from Player One’s turn to Player Two’s turn.

One Turn to Another - this.changePlayer()

The last method we need to declare for this class at the moment is changePlayer.

This will toggle the active player - which in turn affects whether a circle or cross is placed on the board. For some added effect, we’ll also create a new html element to display a message that says who’s turn it is.

  this.changePlayer = function () {
    //  Switch the active player

    if (this.currentPlayer == 0) {
      this.currentPlayer = 1;
    } else {

      this.currentPlayer = 0;
    }
 
    //  Get a reference to our 'message' element and create the message
    var box = document.getElementById('message');
    var msg = "It is " + this.players[this.currentPlayer] + "'s turn.";
    var txt = document.createTextNode(msg);

 
    //  Erase any existing text
    while (box.hasChildNodes()) {
      box.removeChild(box.lastChild);
    }

 
    //  Add the text node (our message) to our element
    box.appendChild(txt);
  }

Again, this is pretty straightforward. The DOM functions are amazingly simple - once you see how they work.

‘box’ is a reference to our element (id = message). The msg variable is a temp variable I created to hold the string. The ‘createTextNode’ method creates a new block of text (with our msg) that we can then insert into an HTML element.

The while() loop is simply there to erase any old text. As long as our ‘box’ element has any child nodes inside of it (text or other HTML tags), the loop will execute and delete one of those child nodes each time. This way we have a clean slate on which to write down who’s turn it is.

Read the full second tutorial here.

Although the tutorial only shows a simplistic tic-tac-toe game you could use the concepts as a starting point to build your own web games. As always if you have made any cool games we would love to hear about them either in the comments or you can write a blog post about it using your free Ajaxonomy account.

Help Your Site Users with a Step By Step Tour

Tagged:  

Have you ever made an incredible web application that you think is very intuitive to users, just to be told by a friend or user that they couldn't figure it out? Often our knowledge of our applications blinds us to the fact that everything may not be as simple to use as we thought.

Because of this common problem Christian Heilmann has written a good solution to the problem called Step by Step. The script displays a sort of tool tip that walks you through a site step by step.

Below is how the script is explained by Chris.

You might have encountered interactive demos created with screencasting and screengrabbing software that explain an interface to users in a step-by-step manner. This is exactly what this script does for web sites.

When you loaded this page and all went well you'll have seen the examples, download and first paragraph section being highlighted and a small panel with information showing up in succession. This is done with this script.

The script uses the Yahoo! User Interface (yet another good example of the library) for the effects, so it does have that dependency.

You can go to the official website here and you can download the code and examples here. To view the examples click here.

If you use this or any other similar script I would love to hear about them. You can leave them in the comments or write a post about them on this blog using your free Ajaxonomy account.

Ajax Security

Tagged:  

Over at Reg Developer they have posted a good article regarding Ajax security. The article takes a 1-2-3 approach to security and covers topics like cross site scripting and SQL injection.

Below is an excerpt from the article.

Know what runs where

AJAX is making it increasingly difficult to be sure where your code is going to run. Take the Google Web Toolkit (GWT) for example. You program in Java and the environment takes some of that code and compiles it to JavaScript that runs on the client. If you make a mistake and implement authentication, access control, validation, or other security checks in the code that runs on the client, an attacker can simply bypass them with Firebug.

Imagine you've carefully coded rules to be sure that administrative functions are never shown to ordinary users. This sounds good, but you forgot that the user interface code is running on the client. So the attacker uses Firebug to invoke the administrative functions. If the proper checks aren't in place on the server side, the attacker just gained administrative rights. Many Rich Internet Application (RIA) frameworks also have this issue.

The solution is to be very careful about making the boundary between the client and the server very clear.

Keep data separate from code

Hackers frequently use a technique called "injection" to bury commands inside innocent-looking data and get interpreters to execute their commands for them. This simple trick is at the heart of many security attacks including SQL injection, command injection, LDAP injection, XSS, and buffer overflows. Preventing injection in a target-rich environment like the modern browser takes discipline.

The key to stopping injection attacks is never executing data that might contain code. But with AJAX, lots of data and code get passed around and mashed together in the DOM. There has never been a data structure that mixes together code and data more than modern HTML.

So be very careful with data that might include user input. Assume it's an attack unless you've carefully canonicalized, validated, and properly encoded. Imagine you're invoking a REST interface and the request contains user data. The response you receive is a JSON string that includes that user data. Don't evaluate that string until you're sure that there can't be anything but safe data in there. Even just adding that data to the DOM might be enough to get it to execute if there's JavaScript code buried in there.

Beware encoding

Encoding makes everything complicated. Attackers can hide their attacks inside innocent-looking data by encoding it. Back-end systems may recognize the encoding used and execute the attack. Or they may decode the attack and pass it on to a system that's vulnerable to it.

Attackers may use multiple different encoding schemes, or even double encode to tunnel their attacks through innocent systems. There are dozens and dozens of encoding schemes and no way to tell which schemes will be recognized by the interpreters you're using. This makes recognizing attacks very difficult, if not impossible.

Every time you send or receive data both sides have to know the intended encoding. Never try to make a "best effort" attempt to guess the right encoding. You can't prevent an attacker from sending data with some other encoding through the channel, but you don't have to execute it. Here are a few examples:

Set HTTP encoding in the header:

 
   Content-Type: text/xml, charset=utf-8

Use a meta tag in the HTML:


Set XML encoding in the first line of XML documents:

<?xml version="1.0" encoding="utf-8"?>

You can read the full post here.

Ajax security is very important in developing your Ajax applications and it is something that many developers overlook.

Online Presentation Applications

Tagged:  

Over at Mashable they have posted a run down of 13 Online Presentation Applications. So get your favorite Business Analyst and show them how they can use the web for their next presentation (although it may take some work as they may be lost outside of the Microsoft PowerPoint world).

Below are the first five listed in the post.

http://us.ajax13.com/en/ajaxpresents/index.jsp

AjaxPresents - Presentation software portion of the Ajax13 office suite. Works with Firefox 1.5 and higher, free, and can import & export from PowerPoint and OpenOffice.

http://www.brinkpad.com

BrinkPad.com - A Java based presentation tool that allows you to create online and then download to your system to save it.

http://www.empressr.com/

Empressr.com - A tool for creating media rich presentations online with Flash and Ajax. You can share them with the public and allow them to be voted on.

Presentation Editor

Google Documents - Google made their intentions to take on Microsoft Office fairly obvious when they finally added an online presentation tool to take on PowerPoint.

http://preezo.com/

Preezo.com - Uses an Ajax-based interface for quick editing. Allows collaboration and easy sharing with clients and colleagues.

You can see the full list by clicking here.

Some of these tools look very good although I don't think that they will replace PowerPoint quite yet.

Reddit Outage - Promoting Ron Paul

Tagged:  

I just went to Reddit to see what was happening on the social network to find that the network is down (it is having a 503 - service not available issue). It is possible that the outage is due to some type of upgrade, but I'm not sure.

What I really thought was interesting is that Reddit has a link to Ron Paul's web site. Could you imagine the outcry from half the Digg community if they did the same thing? I'm not sure if this means that they are supporting Ron Paul or just pandering to their audience as Ron Paul has a huge support on the internet (although it hasn't translated to votes). Either way it is interesting to see how Reddit does not seem to have the same problem with Ron Paul content as Digg does.

Update: Reddit appears to be back up.

Google's Oregon Data Center Blueprints

Tagged:  

Today I ran across an interesting article from Harper's Magazine regarding the blue prints of the Google data center at The Dalles, Oregon. The article mainly focuses the amount of energy that the data center uses and the methods of getting the energy.

You can see the blue prints of the data center here.

You can read the article here.

It is interesting to see how one of the Google data centers is laid out. The next time you search on Google (and you know that almost everybody uses the Google search engine) perhaps your search will go through Google's data center at The Dalles, Oregon.

Create Resizing Thumbnails

Tagged:  

Have you ever been designing a web page or web application that displayed quite a few thumbnails? Perhaps at times it would be nice to have larger thumbnails, but the page design didn't allow for it. Well over at cssglobe.com they have an interesting post about resizing thumbnails so you can enlarge the thumbnails when the mouse is over the thumbnail.

Below is an excerpt from the post.

The Concept

The idea behind this is, to place an image into a certain container. Since we're talking about thumbnails that container would be an <a> tag. We set the size (width and height) of the container to desired values and we set the position property of the container to relative. Image inside has an absolute position. We use negative top and left values to offset the image. Container has overflow set to hidden so only a part of the image that is placed inside the container's actual area will be visible. The rest of it will be hidden. On a:hover we set the container's overflow to visible, and reveal entire image.

overflow thumbnails

The Code

This trick can be used for thumbnail lists or single thumbnails, as shown on the demo page. For markup we use standard tags

<a href="#"><img src="image.jpg"  alt="my image" /></a>

Definition of the default state for thumbnails would be something like this:


	ul#thumbs a{
		display:block;
		float:left;
		width:100px;
		height:100px;
		line-height:100px;
		overflow:hidden;
		position:relative;
		z-index:1;		
	}
	ul#thumbs a img{
		float:left;
		position:absolute;
		top:-20px;
		left:-50px;	
	}

<a> tag has defined width and height to whatever fits into our site's design. Also, overflow is set to hidden. We then play with negative top and left values to "crop" the image to a perfect fit. If you want to take this further, you can define cropping area for every single image you have in thumb list and target the area you would like to show.

 	
	ul#thumbs a img{
		float:left;
		position:absolute;
		top:-20px;
		left:-50px;	
	}
	ul#thumbs li#image1 a img{
		top:-28px;
		left:-55px;	
	}	
	ul#thumbs li#image2 a img{
		top:-18px;
		left:-48px;	
	}	
	ul#thumbs li#image3 a img{
		top:-21px;
		left:-30px;	
	}	
	.
	.
	.		

Now, when user mouse-overs it we set the overflow to visible:

		ul#thumbs a:hover{
			overflow:visible;
			z-index:1000;
			border:none;		
		}

Note the z-index for both default and hovered container. This is very important because we want to place the hovered above it's siblings. Otherwise it would be placed below and the trick wouldn't be complete.

You can read the full post here.

You can view the demo here and you can download the code here.

If you use this on any sites or applications, I'd love to hear about them. You can post them in the comments or you can write a post on this blog once you sign-up for a free account.

Yahoo! and MySpace - Games and Partnerships

Tagged:  

A lot is happening over at MySpace and Yahoo! these days.

First MySpace has launched a new game section that is loaded with Flash games including multi-player games. Warning many of these games will cause a lack of productivity. As is normal on MySpace you can add games that you like to your profile to share it with your friends (although can you imagine how much longer this could make some profiles load). You can click here to go to the games.

Even bigger news is the possibility of a partnership between News Corp (owners of MySpace) and Yahoo. Below is an excerpt of the Mashable post of the rumored partnership.

A report out this afternoon in The Wall Street Journal pumps life back into the rumor that Yahoo and News Corp are negotiating a deal that would trade MySpace and other Fox Interactive properties for a significant stake in Yahoo.

According to the Journal, the negotiations hinge on valuations; News Corp wants MySpace to be valued between $6 and $10 billion, while Yahoo needs to come in with a valuation that beats Microsoft’s $44.6 billion offer to stand any chance. Adding up the numbers between MySpace and other News Corp properties such as IGN, plus a likely infusion of cash, the WSJ says the stake in Yahoo could be more than 20 percent.

The rumor of a News Corp-Yahoo alliance is nothing new – there was significant chatter about the possibilities as recently as last summer. But with Yahoo seemingly desperate to avoid falling into Microsoft’s hands, it’s not surprising they are resuming talks.

Once again, I’m left not seeing a way that any sort of News Corp alliance is going to maximize value for shareholders of either company, especially with Yahoo and News Corp both going into the talks with valuation numbers grounded in nothing other than self-interest. Similar to Microsoft making a relatively small investment in Facebook that valued the company at $15 billion – just because Yahoo and News Corp say the deal makes Yahoo worth $50 billion and MySpace worth $10 billion doesn’t mean the public markets will see it that way (which, is all that really matters).

You can read more about it at Mashable.

I would love to hear your thoughts on all of this news. As always you can either comment on it or you can write your own post on this blog if you sign-up for a free account.

Upgrading to Prototype 1.6 just got easier

Here's some good news for those of you who still need to upgrade your Prototype 1.5 code to Prototype 1.6. Tobie Langel, a core developer on the Prototype team, has developed a script that will warn you of any deprecations or API changes between versions. If you don't know why you should upgrade to 1.6, check out the release info for version 1.6, including the changelog and release notes for 1.6.0_rc0 and 1.6.0_rc1. The script is used with Firebug and is Firefox only, but once you've upgraded, you're good to go in all browsers.

Using the script is easy. To migrate a page from 1.5 to 1.6:

  1. Find the script tag that references prototype.js. Change the path to point to the 1.6.0.2 version (or else overwrite the existing prototype.js with the new version).
  2. On the very next line, add a script tag that references deprecation.js.
  3. Develop your app as normal.

When your code calls a method that’s been deprecated, replaced, or modified, the script will log a warning or error to your Firebug console. Clicking its hyperlink will take you to the deprecation script itself, which isn’t all that helpful; but the message itself will contain a stack trace that points to the source of the error.

Download the deprecation script.

Read more about the script over at the Prototype blog.

Syndicate content