001 /*
002 * Apache License
003 * Version 2.0, January 2004
004 * http://www.apache.org/licenses/
005 *
006 * Copyright 2008-2010 by chenillekit.org
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 */
014
015 package org.chenillekit.tapestry.core.components;
016
017 import org.apache.tapestry5.BindingConstants;
018 import org.apache.tapestry5.ComponentResources;
019 import org.apache.tapestry5.MarkupWriter;
020 import org.apache.tapestry5.annotations.Parameter;
021 import org.apache.tapestry5.annotations.SupportsInformalParameters;
022 import org.apache.tapestry5.ioc.annotations.Inject;
023 import org.slf4j.Logger;
024
025 import javax.swing.text.MaskFormatter;
026
027 /**
028 * <code>MaskFormat</code> is used to format strings. The behavior
029 * of a <code>MaskFormat</code> is controlled by way of a String mask
030 * that specifies the valid characters.
031 * <p/>
032 * for more informations <a target="blank" href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/MaskFormatter.html">click here</a>
033 *
034 * @version $Id: MaskFormat.java 645 2010-03-11 13:05:54Z homburgs $
035 */
036 @SupportsInformalParameters
037 public class MaskFormat
038 {
039 @Inject
040 private Logger logger;
041 /**
042 * the string value
043 */
044 @Parameter(required = true)
045 private String value;
046
047 /**
048 * the format mask
049 */
050 @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
051 private String mask;
052
053 /**
054 * the placeholder character
055 */
056 @Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
057 private String placeholder;
058
059 /**
060 * the valid characters
061 */
062 @Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
063 private String validCharacters;
064
065 /**
066 * ComponentResources. For blocks, messages, crete actionlink, trigger event
067 */
068 @Inject
069 private ComponentResources resources;
070
071 private String getFormatedValue()
072 {
073 try
074 {
075 MaskFormatter mf = new javax.swing.text.MaskFormatter(mask);
076 mf.setValueContainsLiteralCharacters(false);
077
078 if (placeholder != null)
079 mf.setPlaceholderCharacter(placeholder.toCharArray()[0]);
080
081 if (validCharacters != null)
082 mf.setValidCharacters(validCharacters);
083
084 return mf.valueToString(value);
085 }
086 catch (Exception e)
087 {
088 logger.error(e.getLocalizedMessage());
089 return value;
090 }
091 }
092
093 void beginRender(MarkupWriter writer)
094 {
095 String formattedValue = getFormatedValue();
096
097 if (logger.isDebugEnabled())
098 logger.debug("parameter value: %s / transformed value: %s", value, formattedValue);
099
100 writer.element("span");
101 resources.renderInformalParameters(writer);
102 writer.write(formattedValue);
103 writer.end();
104 }
105 }