All-You-Can-Gulp Steamin' Hot Hard-Core Java! No-compromise, professional, non-newbie tips, tricks and solutions. You're invited to join!

Thursday, April 11, 2002

Utility Function of the Day

The following example class makes use of JDK 1.4's new Regular Expression classes (In the java.util.regex package) to create a printf(...)-like function.
The comments contain all the information you'll require, so without further ado:

The Code:
import  java.util.*;

import java.util.regex.*;


/**
* Class to show the Regular Expresion example
*/
public class FormatExample
{


/**
* Similar to C's printf(...) routine, this method takes an input string with
* embedded opcodes and replaces these opcodes with the content of specified
* arguments.
*
* The op-code is %{argument_name}, where "argument_name" is the key-name in the
* specified Properties object that holds the content to fill-in.
*
* An example of a string to format would be:
* "Welcome %{user_name} and good %{day_part}!"
* The Properties object contains two entries:
* "user_name" which contains, for example "John Smith" and
* "day_part" which contains, for example: "morning".
* The resulting string is:
* "Welcome John Smith and good morning!"
*
* You could also place any other object as the value for the argument,
* as the routine automatically does a "toString()" call to convert the
* value of the argument to a string.
*
* @param formatString The string to format
* @param arguments By-name hash of arguments to fill-in
* @return Fully qualified string with all references resolved.
* @author Tal Rotbart
*/
public static String format(String formatString, Properties arguments)
{
StringBuffer formattedString = new StringBuffer(formatString.length() * 2);
Pattern tokenRegex = Pattern.compile("%\\{[\\p{Alnum}\\p{Punct}]*\\}");

if ((arguments == null) || (arguments.size() <= 0))
{
return formatString;
}

Matcher matcher = tokenRegex.matcher(formatString);

/**
* Match the %{n} instances and replace them with the specified string argument
*/
while (matcher.find())
{
/**
* Take the matched argument name and use it
*/
String argumentNameString = formatString.substring(matcher.start() + 2, matcher.end() - 1);
Object argumentValue = arguments.get(argumentNameString);

/**
* If we do not have the argument, it doesn't mean we have to choke, it may be filled at a later "format" call.
*/
if (argumentValue != null)
{
/**
* Recursively resolve the referenced string resources
*/
matcher.appendReplacement(formattedString, argumentValue.toString());
}
}


/**
* Append everything after the last match, or from the top if no match
*/
matcher.appendTail(formattedString);

return formattedString.toString();
}


/**
* Main method for testing the "format" routine.
*/
public static void main(String[] args)
{
String formatString = "Welcome %{user_name}! Have a good %{day_part}!";
Properties formatProperties = new Properties();

formatProperties.setProperty("user_name", "John Smith");
formatProperties.setProperty("day_part", "evening");

System.out.println("Result = \"" + format(formatString, formatProperties) + "\".");
}


}




Enjoy :)

Wednesday, April 10, 2002

Utility Function of the Day

The following method mixes several colors together according to a specified bias thus creating a new color. It is a very useful function for custom user-interface components, especially if they are to be affected by user-customization.

For example:
Consider a calendar-widget that has different color codes for different types of holidays (by religion perhaps). You can use this function to calculate the selection color for a specific day by mixing the global (user-chosen?) selection color with the specific day's color and even to go further and to mix several colors when holidays intersect.

How it works:
The specified Color objects are split to their individual color-components or channels (red, gree, blue and alpha) which are then collected while being multiplied by the per-color bias. Then, an average value for each color component is calculated based on the collected channels and used to create a new Color object.

Note:
Make sure to remember to cache the resulting Color object for re-use whenever possible! Object-Creation-Is-Expensive(tm).

The Code:
  public  static  Color mixColors(Color[] colorsToMix,  float[] colorBias)

{
long red = 0;
long green = 0;
long blue = 0;
long alpha = 0;

for (int i = 0; i < colorsToMix.length; i++)
{
Color currentColor = colorsToMix[i];
float currentBias = colorBias[i];

red += currentColor.getRed() * currentBias;
green += currentColor.getGreen() * currentBias;
blue += currentColor.getBlue() * currentBias;
alpha += currentColor.getAlpha() * currentBias;
}

red /= colorsToMix.length;
green /= colorsToMix.length;
blue /= colorsToMix.length;
alpha /= colorsToMix.length;

return new Color((int)red, (int)green, (int)blue, (int)alpha);
};




Enjoy!

Welcome to Java*Gulp*!

We've created this site for those of us Java hard-core pros that are sick-and-tired of the low signal-to-noise ratio on the general Java sites, forums and mailing-lists and are looking for true high-level hard-core professional-grade Java knowledge, advice and information -- without the buzzword-intensive newbie/drone noise.

This is a -highly- moderated weblog -- only good(tm) software-engineers that have enterprise-grade experience write here -- if your level of application design has been limited to the "Visual *Whatever* for Dummies" level, you won't find your place here.