Java tutorial
/** * Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.com/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ // Revised from ajax4jsf import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.regex.Pattern; public class HtmlDimensions { private static final Pattern PATTERN_NUMERIC = Pattern.compile("^[+-]?\\d+(\\.\\d+)?$"); private static final Pattern PATTERN_PX = Pattern.compile("^[+-]?\\d+(\\.\\d+)?px$"); private static final Pattern PATTERN_PCT = Pattern.compile("^[+-]?\\d+(\\.\\d+)?%$"); private static final NumberFormat numericFormat = new DecimalFormat(); private static final DecimalFormat pxFormat = new DecimalFormat(); private static final NumberFormat pctFormat = NumberFormat.getPercentInstance(); static { pxFormat.setPositiveSuffix("px"); pxFormat.setNegativeSuffix("px"); } public static Double decode(String size) { // TODO - handle px,ex,pt enc suffixes. double d = 0; try { if (size != null) { if (PATTERN_NUMERIC.matcher(size).matches()) { synchronized (numericFormat) { d = numericFormat.parse(size).doubleValue(); } } else if (PATTERN_PX.matcher(size).matches()) { synchronized (pxFormat) { d = pxFormat.parse(size).doubleValue(); } } else if (PATTERN_PCT.matcher(size).matches()) { synchronized (pctFormat) { d = pctFormat.parse(size).doubleValue(); } } } } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } return new Double(d); } public static String formatPx(Double value) { return (value.intValue() + "px"); } public static String formatPct(Double value) { String v = ""; synchronized (pctFormat) { v = pctFormat.format(value.doubleValue()); } return v; } }