View Javadoc

1   /*
2    * Copyright 2004 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.nordija.tapestry.bayeux.insert;
17  
18  import org.apache.hivemind.ApplicationRuntimeException;
19  import org.apache.tapestry.IMarkupWriter;
20  import org.apache.tapestry.IRequestCycle;
21  import org.apache.tapestry.components.Insert;
22  
23  import java.text.Format;
24  
25  /**
26   * Outputs a limited string from the underlying object. Works as Insert.
27   *
28   * @author Thomas Christensen www.nordija.com
29   * @version $Id$
30   */
31  public abstract class InsertLimited extends Insert {
32  
33      public abstract int getMaxLength();
34  
35      public abstract String getMoreMarker();
36  
37      /**
38       * Prints its value parameter, possibly formatted by its format parameter.
39       */
40      protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) {
41          if (cycle.isRewinding())
42              return;
43  
44          Object value = getValue();
45  
46          if (value == null)
47              return;
48  
49          String insert;
50  
51          Format format = getFormat();
52  
53          if (format == null) {
54              insert = value.toString();
55          } else {
56              try {
57                  insert = format.format(value);
58              }
59              catch (Exception ex) {
60                  throw new ApplicationRuntimeException(InsertMessages.unableToFormat(this, value, ex), this, getBinding(
61                          "format").getLocation(), ex);
62              }
63          }
64  
65          //added to be able to insert a limited amount of text
66          if (!getRaw() && insert.length() > getMaxLength()) {
67              if (getMoreMarker() == null) {
68                  insert = insert.substring(0, getMaxLength());
69              } else {
70                  insert = insert.substring(0, getMaxLength() - getMoreMarker().length()) + getMoreMarker();
71              }
72          }
73  
74          boolean render = getRenderTag() || isParameterBound("class");
75  
76          if (render) {
77              writer.begin(getTemplateTagName());
78  
79              renderInformalParameters(writer, cycle);
80          }
81  
82          printText(writer, cycle, insert);
83  
84          if (render) {
85              writer.end();
86          }
87      }
88  }