Monday, July 30, 2012

C#-like TryParse Integer for Java

public static Integer TryParseInt(String someText) {
try {
return Integer.parseInt(someText);
} catch (NumberFormatException ex) {
return null;
}
}

Thursday, May 24, 2012

[AppEngine] java.lang.RuntimeException: Unable to restore the previous TimeZone

Started getting the error on the dev server after upgrading to AppEngine 1.6.3 on Mac.

Turns out AppEngine is looking (via reflection) for a field that's missing from JDK 6.

You can either use a different JDK or add the following to the VM arguments from run configuration (which did the trick for me):
-Dappengine.user.timezone=UTC

Wednesday, May 9, 2012

Javascript Random Masking

Just a snippet to randomly mask some text, for whatever reason (such as not getting sued).

String.prototype.replaceAt=function(index, char) {
return this.substr(0, index) + char + this.substr(index+char.length);
}
var REPLACEMENT_CHAR = "*";
var TO = 5;
var FROM = 4;
var str = "Hello World";
var strLen = str.length;
var rnd = Math.floor((Math.random()*(TO - FROM + 1)) + FROM);
for(i = 0; i < strLen; i++){
if((i+1) >= rnd && ((i+1) % rnd) == 0 && str.charAt(i) != " " && str.charAt(i) != REPLACEMENT_CHAR)
{
str = str.replaceAt(i, REPLACEMENT_CHAR);
}
}
alert(str);

Saturday, February 11, 2012

Javascript Profanity Check

Here's a copy-paste-ready snippet implementing a javascript profanity check:

// extend strings with the method "contains"
String.prototype.contains = function(str) { return this.indexOf(str) != -1; };
// profanities of choice
var profanities = new Array("ass", "cunt", "pope");
var containsProfanity = function(text){
var returnVal = false;
for (var i = 0; i < profanities.length; i++) {
if(text.toLowerCase().contains(profanities[i].toLowerCase())){
returnVal = true;
break;
}
}
return returnVal;
}
var myText = $('#text').html();
if(containsProfanity(myText)){
$('#result').html('That language is profane dude.');
}
else{
$('#result').html('That language is just fine.');
}
Enjoy.

Friday, February 3, 2012

Use of com.google.appengine.repackaged may result in your app breaking without warning.

I got this nasty error on the repackaged version of Base64 after upgrading to app-engine 1.6.1 on a project:

Use of com.google.appengine.repackaged may result in your app breaking without warning.

You can make it go away by switching to org.apache.commons.codec.binary.Base64, that can be found on the commons-codec library. Mapping of the encode/decode methods is pretty straightforward:
  • encode --> encodeBase64String
  • decode --> decodeBase64
Or something like that.