001    // Copyright 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry;
016    
017    import java.util.ArrayList;
018    import java.util.List;
019    
020    import org.apache.hivemind.ApplicationRuntimeException;
021    import org.apache.hivemind.HiveMind;
022    import org.apache.hivemind.Location;
023    import org.apache.hivemind.util.Defense;
024    
025    /**
026     * Constants and static methods.
027     * 
028     * @author Howard M. Lewis Ship
029     * @since 4.0
030     */
031    public final class TapestryUtils
032    {
033        public static final String PAGE_RENDER_SUPPORT_ATTRIBUTE = "org.apache.tapestry.PageRenderSupport";
034    
035        public static final String FORM_ATTRIBUTE = "org.apache.tapestry.Form";
036        
037        public static final String FIELD_PRERENDER = "org.apache.tapestry.form.Prerender";
038        
039        private static final char QUOTE = '\'';
040    
041        private static final char BACKSLASH = '\\';
042    
043        private static final String EMPTY_QUOTES = "''";
044    
045        /* defeat instantiation */
046        private TapestryUtils() { }
047        
048        /**
049         * Stores an attribute into the request cycle, verifying that no object with that key is already
050         * present.
051         * 
052         * @param cycle
053         *            the cycle to store the attribute into
054         * @param key
055         *            the key to store the attribute as
056         * @param object
057         *            the attribute value to store
058         * @throws IllegalStateException
059         *             if a non-null value has been stored into the cycle with the provided key.
060         */
061    
062        public static void storeUniqueAttribute(IRequestCycle cycle, String key, Object object)
063        {
064            Defense.notNull(cycle, "cycle");
065            Defense.notNull(key, "key");
066            Defense.notNull(object, "object");
067    
068            Object existing = cycle.getAttribute(key);
069            if (existing != null)
070                throw new IllegalStateException(TapestryMessages.nonUniqueAttribute(
071                        object,
072                        key,
073                        existing));
074    
075            cycle.setAttribute(key, object);
076        }
077    
078        /**
079         * Stores the support object using {@link #storeUniqueAttribute(IRequestCycle, String, Object)}.
080         */
081    
082        public static void storePageRenderSupport(IRequestCycle cycle, PageRenderSupport support)
083        {
084            storeUniqueAttribute(cycle, PAGE_RENDER_SUPPORT_ATTRIBUTE, support);
085        }
086    
087        /**
088         * Store the IForm instance using {@link #storeUniqueAttribute(IRequestCycle, String, Object)}.
089         */
090    
091        public static void storeForm(IRequestCycle cycle, IForm form)
092        {
093            storeUniqueAttribute(cycle, FORM_ATTRIBUTE, form);
094        }
095    
096        /**
097         * Stores the {@link IComponent} into the cycle by FormSupport before doing a field
098         * prerender.
099         * @param cycle
100         * @param component
101         */
102        public static void storePrerender(IRequestCycle cycle, IComponent component)
103        {
104            storeUniqueAttribute(cycle, FIELD_PRERENDER, component);
105        }
106        
107        /**
108         * Gets the previously stored {@link org.apache.tapestry.PageRenderSupport} object.
109         * 
110         * @param cycle
111         *            the request cycle storing the support object
112         * @param component
113         *            the component which requires the support (used to report exceptions)
114         * @throws ApplicationRuntimeException
115         *             if no support object has been stored
116         */
117    
118        public static PageRenderSupport getPageRenderSupport(IRequestCycle cycle, IComponent component)
119        {
120            Defense.notNull(component, "component");
121    
122            PageRenderSupport result = getOptionalPageRenderSupport(cycle);
123            if (result == null)
124                throw new ApplicationRuntimeException(TapestryMessages.noPageRenderSupport(component),
125                        component.getLocation(), null);
126    
127            return result;
128        }
129    
130        /**
131         * Gets the previously stored {@link IForm} object.
132         * 
133         * @param cycle
134         *            the request cycle storing the support object
135         * @param component
136         *            the component which requires the form (used to report exceptions)
137         * @throws ApplicationRuntimeException
138         *             if no form object has been stored
139         */
140        public static IForm getForm(IRequestCycle cycle, IComponent component)
141        {
142            Defense.notNull(cycle, "cycle");
143            Defense.notNull(component, "component");
144    
145            IForm result = (IForm) cycle.getAttribute(FORM_ATTRIBUTE);
146    
147            if (result == null)
148                throw new ApplicationRuntimeException(TapestryMessages.noForm(component), component
149                        .getLocation(), null);
150    
151            return result;
152        }
153    
154        public static void removePageRenderSupport(IRequestCycle cycle)
155        {
156            cycle.removeAttribute(PAGE_RENDER_SUPPORT_ATTRIBUTE);
157        }
158    
159        public static void removeForm(IRequestCycle cycle)
160        {
161            cycle.removeAttribute(FORM_ATTRIBUTE);
162        }
163        
164        public static void removePrerender(IRequestCycle cycle)
165        {
166            cycle.removeAttribute(FIELD_PRERENDER);
167        }
168        
169        /**
170         * Returns the {@link PageRenderSupport} object if previously stored, or null otherwise.
171         * This is used in the rare case that a component wishes to adjust its behavior based on whether
172         * the page render support services are available (typically, adjust for whether enclosed by a
173         * Body component, or not).
174         */
175    
176        public static PageRenderSupport getOptionalPageRenderSupport(IRequestCycle cycle)
177        {
178            return (PageRenderSupport) cycle.getAttribute(PAGE_RENDER_SUPPORT_ATTRIBUTE);
179        }
180    
181        /**
182         * Splits a string using the default delimiter of ','.
183         */
184    
185        public static String[] split(String input)
186        {
187            return split(input, ',');
188        }
189    
190        /**
191         * Splits a single string into an array of strings, using a specific delimiter character.
192         */
193    
194        public static String[] split(String input, char delimiter)
195        {
196            if (HiveMind.isBlank(input))
197                return new String[0];
198    
199            List strings = new ArrayList();
200    
201            char[] buffer = input.toCharArray();
202    
203            int start = 0;
204            int length = 0;
205    
206            for (int i = 0; i < buffer.length; i++)
207            {
208                if (buffer[i] != delimiter)
209                {
210                    length++;
211                    continue;
212                }
213    
214                // Consecutive delimiters will result in a sequence
215                // of empty strings.
216    
217                String token = new String(buffer, start, length);
218                strings.add(token);
219    
220                start = i + 1;
221                length = 0;
222            }
223    
224            // If the string contains no delimiters, then
225            // wrap it an an array and return it.
226    
227            if (start == 0 && length == buffer.length)
228            {
229                return new String[]
230                { input };
231            }
232    
233            // The final token.
234            String token = new String(buffer, start, length);
235            strings.add(token);
236    
237            return (String[]) strings.toArray(new String[strings.size()]);
238        }
239    
240        /**
241         * Enquotes a string within single quotes, ready for insertion as part of a block of JavaScript.
242         * Single quotes and backslashes within the input string are properly escaped.
243         */
244    
245        public static String enquote(String input)
246        {
247            if (input == null)
248                return EMPTY_QUOTES;
249    
250            char[] chars = input.toCharArray();
251    
252            // Add room for the two quotes and a couple of escaped characters
253    
254            StringBuffer buffer = new StringBuffer(chars.length + 5);
255    
256            buffer.append(QUOTE);
257    
258            for (int i = 0; i < chars.length; i++)
259            {
260                char ch = chars[i];
261    
262                if (ch == QUOTE || ch == BACKSLASH)
263                    buffer.append(BACKSLASH);
264    
265                buffer.append(ch);
266            }
267    
268            buffer.append(QUOTE);
269    
270            return buffer.toString();
271        }
272    
273        /**
274         * A Tapestry component id is a little more liberal than an XML NMTOKEN. NMTOKEN must be
275         * [A-Za-z][A-Za-z0-9:_.-]*, but a component id might include a leading dollar sign (for an
276         * anonymous component with a fabricated id).
277         */
278    
279        public static String convertTapestryIdToNMToken(String baseId)
280        {
281            String result = baseId.replace('$', '_');
282    
283            while (result.startsWith("_"))
284                result = result.substring(1);
285    
286            return result;
287        }
288    
289        /**
290         * Converts a clientId into a client-side DOM reference; i.e.
291         * <code>document.getElementById('<i>id</i>')</code>.
292         */
293    
294        public static String buildClientElementReference(String clientId)
295        {
296            Defense.notNull(clientId, "clientId");
297    
298            return "document.getElementById('" + clientId + "')";
299        }
300    
301        /**
302         * Used by some generated code; obtains a component and ensures it is of the correct type.
303         */
304    
305        public static IComponent getComponent(IComponent container, String componentId,
306                Class expectedType, Location location)
307        {
308            Defense.notNull(container, "container");
309            Defense.notNull(componentId, "componentId");
310            Defense.notNull(expectedType, "expectedType");
311            // Don't always have a location
312    
313            IComponent component = null;
314    
315            try
316            {
317                component = container.getComponent(componentId);
318            }
319            catch (Exception ex)
320            {
321                throw new ApplicationRuntimeException(ex.getMessage(), location, ex);
322            }
323    
324            if (!expectedType.isAssignableFrom(component.getClass()))
325                throw new ApplicationRuntimeException(TapestryMessages.componentWrongType(
326                        component,
327                        expectedType), location, null);
328    
329            return component;
330        }
331    }