View Javadoc

1   /**
2    * Copyright 2005-2013 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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 org.kuali.rice.krad.uif.util;
17  
18  import org.apache.commons.lang.ArrayUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.kuali.rice.krad.uif.component.Component;
21  import org.kuali.rice.krad.uif.element.Message;
22  import org.kuali.rice.krad.uif.view.View;
23  import org.kuali.rice.krad.util.KRADConstants;
24  
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.List;
28  
29  /**
30   * Rich message structure utilities for parsing message content and converting it to components/content
31   *
32   * @author Kuali Rice Team (rice.collab@kuali.org)
33   */
34  public class MessageStructureUtils {
35  
36      /**
37       * Translate a message with special hooks described in MessageStructureUtils.parseMessage.  However, tags which
38       * reference components will not be allowed/translated - only tags which can translate to string content will
39       * be included for this translation.
40       *
41       * @param messageText messageText with only String translateable tags included (no id or component index tags)
42       * @return html translation of rich messageText passed in
43       * @see MessageStructureUtils#parseMessage
44       */
45      public static String translateStringMessage(String messageText) {
46          if (!StringUtils.isEmpty(messageText)) {
47              List<Component> components = MessageStructureUtils.parseMessage(null, messageText, null, null, false);
48  
49              if (!components.isEmpty()) {
50                  Component message = components.get(0);
51  
52                  if (message instanceof Message) {
53                      messageText = ((Message) message).getMessageText();
54                  }
55              }
56          }
57  
58          return messageText;
59      }
60  
61      /**
62       * Parses the message text passed in and returns the resulting rich message component structure.
63       *
64       * <p>If special characters [] are detected the message is split at that location.  The types of features supported
65       * by the parse are (note that &lt;&gt; are not part of the content, they specify placeholders):
66       * <ul>
67       * <li>[id=&lt;component id&gt;] - insert component with id specified at that location in the message</li>
68       * <li>[n] - insert component at index n from the inlineComponent list</li>
69       * <li>[&lt;html tag&gt;][/&lt;html tag&gt;] - insert html content directly into the message content at that
70       * location,
71       * without the need to escape the &lt;&gt; characters in xml</li>
72       * <li>[color=&lt;html color code/name&gt;][/color] - wrap content in color tags to make text that color
73       * in the message</li>
74       * <li>[css=&lt;css classes&gt;][/css] - apply css classes specified to the wrapped content - same as wrapping
75       * the content in span with class property set</li>
76       * <li>[link=&lt;href src&gt;][/link] - an easier way to create an anchor that will open in a new page to the
77       * href specified after =</li>
78       * <li>[action=&lt;href src&gt;][/action] - create an action link inline without having to specify a component by
79       * id or index.  The options for this are as follows and MUST be in a comma seperated list in the order specified
80       * (specify 1-4 always in this order):
81       * <ul>
82       * <li>methodToCall(String)</li>
83       * <li>validateClientSide(boolean) - true if not set</li>
84       * <li>ajaxSubmit(boolean) - true if not set</li>
85       * <li>successCallback(js function or function declaration) - this only works when ajaxSubmit is true</li>
86       * </ul>
87       * The tag would look something like this [action=methodToCall]Action[/action] in most common cases.  And in more
88       * complex cases [action=methodToCall,true,true,functionName]Action[/action].  <p>In addition to these settings,
89       * you can also specify data to send to the server in this fashion (space is required between settings and data):
90       * </p>
91       * [action=&lt;action settings&gt; data={key1: 'value 1', key2: value2}]
92       * </li>
93       * </ul>
94       * If the [] characters are needed in message text, they need to be declared with an escape character: \\[ \\]
95       * </p>
96       *
97       * @param messageId id of the message
98       * @param messageText message text to be parsed
99       * @param componentList the inlineComponent list
100      * @param view the current view
101      * @return list of components representing the parsed message structure
102      */
103     public static List<Component> parseMessage(String messageId, String messageText, List<Component> componentList,
104             View view, boolean parseComponents) {
105         messageText = messageText.replace("\\" + KRADConstants.MessageParsing.LEFT_TOKEN,
106                 KRADConstants.MessageParsing.LEFT_BRACKET);
107         messageText = messageText.replace("\\" + KRADConstants.MessageParsing.RIGHT_TOKEN,
108                 KRADConstants.MessageParsing.RIGHT_BRACKET);
109         messageText = messageText.replace(KRADConstants.MessageParsing.RIGHT_TOKEN,
110                 KRADConstants.MessageParsing.RIGHT_TOKEN_PLACEHOLDER);
111         String[] messagePieces = messageText.split("[\\" + KRADConstants.MessageParsing.LEFT_TOKEN +
112                 "|\\" + KRADConstants.MessageParsing.RIGHT_TOKEN + "]");
113 
114         List<Component> messageComponentStructure = new ArrayList<Component>();
115 
116         //current message object to concatenate to after it is generated to prevent whitespace issues and
117         //creation of multiple unneeded objects
118         Message currentMessageComponent = null;
119 
120         for (String messagePiece : messagePieces) {
121             if (messagePiece.endsWith(KRADConstants.MessageParsing.RIGHT_TOKEN_MARKER)) {
122                 messagePiece = StringUtils.removeEnd(messagePiece, KRADConstants.MessageParsing.RIGHT_TOKEN_MARKER);
123 
124                 if (StringUtils.startsWithIgnoreCase(messagePiece, KRADConstants.MessageParsing.COMPONENT_BY_ID + "=")
125                         && parseComponents) {
126                     //Component by Id
127                     currentMessageComponent = processIdComponentContent(messagePiece, messageComponentStructure,
128                             currentMessageComponent, view);
129                 } else if (messagePiece.matches("^[0-9]+( .+=.+)*$") && parseComponents) {
130                     //Component by index of inlineComponents
131                     currentMessageComponent = processIndexComponentContent(messagePiece, componentList,
132                             messageComponentStructure, currentMessageComponent, view, messageId);
133                 } else if (StringUtils.startsWithIgnoreCase(messagePiece, KRADConstants.MessageParsing.COLOR + "=")
134                         || StringUtils.startsWithIgnoreCase(messagePiece, "/" + KRADConstants.MessageParsing.COLOR)) {
135                     //Color span
136                     currentMessageComponent = processColorContent(messagePiece, currentMessageComponent, view);
137                 } else if (StringUtils.startsWithIgnoreCase(messagePiece,
138                         KRADConstants.MessageParsing.CSS_CLASSES + "=") || StringUtils.startsWithIgnoreCase(
139                         messagePiece, "/" + KRADConstants.MessageParsing.CSS_CLASSES)) {
140                     //css class span
141                     currentMessageComponent = processCssClassContent(messagePiece, currentMessageComponent, view);
142                 } else if (StringUtils.startsWithIgnoreCase(messagePiece, KRADConstants.MessageParsing.LINK + "=")
143                         || StringUtils.startsWithIgnoreCase(messagePiece, "/" + KRADConstants.MessageParsing.LINK)) {
144                     //link (a tag)
145                     currentMessageComponent = processLinkContent(messagePiece, currentMessageComponent, view);
146                 } else if (StringUtils.startsWithIgnoreCase(messagePiece,
147                         KRADConstants.MessageParsing.ACTION_LINK + "=") || StringUtils.startsWithIgnoreCase(
148                         messagePiece, "/" + KRADConstants.MessageParsing.ACTION_LINK)) {
149                     //action link (a tag)
150                     currentMessageComponent = processActionLinkContent(messagePiece, currentMessageComponent, view);
151                 } else if (messagePiece.equals("")) {
152                     //do nothing    
153                 } else {
154                     //raw html content
155                     currentMessageComponent = processHtmlContent(messagePiece, currentMessageComponent, view);
156                 }
157             } else {
158                 //raw string
159                 messagePiece = addBlanks(messagePiece);
160                 currentMessageComponent = concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
161             }
162         }
163 
164         if (currentMessageComponent != null && StringUtils.isNotEmpty(currentMessageComponent.getMessageText())) {
165             messageComponentStructure.add(currentMessageComponent);
166             currentMessageComponent = null;
167         }
168 
169         return messageComponentStructure;
170     }
171 
172     /**
173      * Concatenates string content onto the message passed in and passes it back.  If the message is null, creates
174      * a new message object with the string content and passes that back.
175      *
176      * @param currentMessageComponent Message object
177      * @param messagePiece string content to be concatenated
178      * @param view the current view
179      * @return resulting concatenated Message
180      */
181     private static Message concatenateStringMessageContent(Message currentMessageComponent, String messagePiece,
182             View view) {
183         if (currentMessageComponent == null) {
184             currentMessageComponent = ComponentFactory.getMessage();
185             currentMessageComponent.setMessageText(messagePiece);
186             currentMessageComponent.setGenerateSpan(false);
187         } else {
188             currentMessageComponent.setMessageText(currentMessageComponent.getMessageText() + messagePiece);
189         }
190 
191         return currentMessageComponent;
192     }
193 
194     /**
195      * Process the additional properties beyond index 0 of the tag (that was split into parts).
196      *
197      * <p>This will evaluate and set each of properties on the component passed in.  This only allows
198      * setting of properties that can easily be converted to/from/are String type by Spring.</p>
199      *
200      * @param component component to have its properties set
201      * @param tagParts the tag split into parts, index 0 is ignored
202      * @return component with its properties set found in the tag's parts
203      */
204     private static Component processAdditionalProperties(Component component, String[] tagParts) {
205         String componentString = tagParts[0];
206         tagParts = (String[]) ArrayUtils.remove(tagParts, 0);
207 
208         for (String part : tagParts) {
209             String[] propertyValue = part.split("=");
210 
211             if (propertyValue.length == 2) {
212                 String path = propertyValue[0];
213                 String value = propertyValue[1].trim();
214                 value = StringUtils.removeStart(value, "'");
215                 value = StringUtils.removeEnd(value, "'");
216                 ObjectPropertyUtils.setPropertyValue(component, path, value);
217             } else {
218                 throw new RuntimeException(
219                         "Invalid Message structure for component defined as " + componentString + " around " + part);
220             }
221         }
222 
223         return component;
224     }
225 
226     /**
227      * Inserts &amp;nbsp; into the string passed in, if spaces exist at the beginning and/or end,
228      * so spacing is not lost in html translation.
229      *
230      * @param text string to insert  &amp;nbsp;
231      * @return String with  &amp;nbsp; inserted, if applicable
232      */
233     public static String addBlanks(String text) {
234         if (StringUtils.startsWithIgnoreCase(text, " ")) {
235             text = "&nbsp;" + StringUtils.removeStart(text, " ");
236         }
237 
238         if (text.endsWith(" ")) {
239             text = StringUtils.removeEnd(text, " ") + "&nbsp;";
240         }
241 
242         return text;
243     }
244 
245     /**
246      * Process a piece of the message that has id content to get a component by id and insert it in the structure
247      *
248      * @param messagePiece String piece with component by id content
249      * @param messageComponentStructure the structure of the message being built
250      * @param currentMessageComponent the state of the current text based message being built
251      * @param view current View
252      * @return null if currentMessageComponent had a value (it is now added to the messageComponentStructure passed in)
253      */
254     private static Message processIdComponentContent(String messagePiece, List<Component> messageComponentStructure,
255             Message currentMessageComponent, View view) {
256         //splits around spaces not included in single quotes
257         String[] parts = messagePiece.trim().trim().split("([ ]+(?=([^']*'[^']*')*[^']*$))");
258         messagePiece = parts[0];
259 
260         //if there is a currentMessageComponent add it to the structure and reset it to null
261         //because component content is now interrupting the string content
262         if (currentMessageComponent != null && StringUtils.isNotEmpty(currentMessageComponent.getMessageText())) {
263             messageComponentStructure.add(currentMessageComponent);
264             currentMessageComponent = null;
265         }
266 
267         //match component by id from the view
268         messagePiece = StringUtils.remove(messagePiece, "'");
269         messagePiece = StringUtils.remove(messagePiece, "\"");
270         Component component = ComponentFactory.getNewComponentInstance(StringUtils.removeStart(messagePiece,
271                 KRADConstants.MessageParsing.COMPONENT_BY_ID + "="));
272 
273         if (component != null) {
274             component.addStyleClass(KRADConstants.MessageParsing.INLINE_COMP_CLASS);
275 
276             if (parts.length > 1) {
277                 component = processAdditionalProperties(component, parts);
278             }
279             messageComponentStructure.add(component);
280         }
281 
282         return currentMessageComponent;
283     }
284 
285     /**
286      * Process a piece of the message that has index content to get a component by index in the componentList passed in
287      * and insert it in the structure
288      *
289      * @param messagePiece String piece with component by index content
290      * @param componentList list that contains the component referenced by index
291      * @param messageComponentStructure the structure of the message being built
292      * @param currentMessageComponent the state of the current text based message being built
293      * @param view current View
294      * @param messageId id of the message being parsed (for exception notification)
295      * @return null if currentMessageComponent had a value (it is now added to the messageComponentStructure passed in)
296      */
297     private static Message processIndexComponentContent(String messagePiece, List<Component> componentList,
298             List<Component> messageComponentStructure, Message currentMessageComponent, View view, String messageId) {
299         //splits around spaces not included in single quotes
300         String[] parts = messagePiece.trim().trim().split("([ ]+(?=([^']*'[^']*')*[^']*$))");
301         messagePiece = parts[0];
302 
303         //if there is a currentMessageComponent add it to the structure and reset it to null
304         //because component content is now interrupting the string content
305         if (currentMessageComponent != null && StringUtils.isNotEmpty(currentMessageComponent.getMessageText())) {
306             messageComponentStructure.add(currentMessageComponent);
307             currentMessageComponent = null;
308         }
309 
310         //match component by index from the componentList passed in
311         int cIndex = Integer.parseInt(messagePiece);
312 
313         if (componentList != null && cIndex < componentList.size() && !componentList.isEmpty()) {
314             Component component = componentList.get(cIndex);
315 
316             if (component != null) {
317                 if (parts.length > 1) {
318                     component = processAdditionalProperties(component, parts);
319                 }
320 
321                 component.addStyleClass(KRADConstants.MessageParsing.INLINE_COMP_CLASS);
322                 messageComponentStructure.add(component);
323             }
324         } else {
325             throw new RuntimeException("Component with index " + cIndex +
326                     " does not exist in inlineComponents of the message component with id " + messageId);
327         }
328 
329         return currentMessageComponent;
330     }
331 
332     /**
333      * Process a piece of the message that has color content by creating a span with that color style set
334      *
335      * @param messagePiece String piece with color content
336      * @param currentMessageComponent the state of the current text based message being built
337      * @param view current View
338      * @return currentMessageComponent with the new textual content generated by this method appended to its
339      *         messageText
340      */
341     private static Message processColorContent(String messagePiece, Message currentMessageComponent, View view) {
342         if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
343             messagePiece = StringUtils.remove(messagePiece, "'");
344             messagePiece = StringUtils.remove(messagePiece, "\"");
345             messagePiece = "<span style='color: " + StringUtils.removeStart(messagePiece,
346                     KRADConstants.MessageParsing.COLOR + "=") + ";'>";
347         } else {
348             messagePiece = "</span>";
349         }
350 
351         return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
352     }
353 
354     /**
355      * Process a piece of the message that has css content by creating a span with those css classes set
356      *
357      * @param messagePiece String piece with css class content
358      * @param currentMessageComponent the state of the current text based message being built
359      * @param view current View
360      * @return currentMessageComponent with the new textual content generated by this method appended to its
361      *         messageText
362      */
363     private static Message processCssClassContent(String messagePiece, Message currentMessageComponent, View view) {
364         if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
365             messagePiece = StringUtils.remove(messagePiece, "'");
366             messagePiece = StringUtils.remove(messagePiece, "\"");
367             messagePiece = "<span class='" + StringUtils.removeStart(messagePiece,
368                     KRADConstants.MessageParsing.CSS_CLASSES + "=") + "'>";
369         } else {
370             messagePiece = "</span>";
371         }
372 
373         return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
374     }
375 
376     /**
377      * Process a piece of the message that has link content by creating an anchor (a tag) with the href set
378      *
379      * @param messagePiece String piece with link content
380      * @param currentMessageComponent the state of the current text based message being built
381      * @param view current View
382      * @return currentMessageComponent with the new textual content generated by this method appended to its
383      *         messageText
384      */
385     private static Message processLinkContent(String messagePiece, Message currentMessageComponent, View view) {
386         if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
387             //clean up href
388             messagePiece = StringUtils.removeStart(messagePiece, KRADConstants.MessageParsing.LINK + "=");
389             messagePiece = StringUtils.removeStart(messagePiece, "'");
390             messagePiece = StringUtils.removeEnd(messagePiece, "'");
391             messagePiece = StringUtils.removeStart(messagePiece, "\"");
392             messagePiece = StringUtils.removeEnd(messagePiece, "\"");
393 
394             messagePiece = "<a href='" + messagePiece + "' target='_blank'>";
395         } else {
396             messagePiece = "</a>";
397         }
398 
399         return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
400     }
401 
402     /**
403      * Process a piece of the message that has action link content by creating an anchor (a tag) with the onClick set
404      * to perform either ajaxSubmit or submit to the controller with a methodToCall
405      *
406      * @param messagePiece String piece with action link content
407      * @param currentMessageComponent the state of the current text based message being built
408      * @param view current View
409      * @return currentMessageComponent with the new textual content generated by this method appended to its
410      *         messageText
411      */
412     private static Message processActionLinkContent(String messagePiece, Message currentMessageComponent, View view) {
413         if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
414             messagePiece = StringUtils.removeStart(messagePiece, KRADConstants.MessageParsing.ACTION_LINK + "=");
415             String[] splitData = messagePiece.split(KRADConstants.MessageParsing.ACTION_DATA + "=");
416 
417             String[] params = splitData[0].trim().split("([,]+(?=([^']*'[^']*')*[^']*$))");
418             String methodToCall = ((params.length >= 1) ? params[0] : "");
419             String validate = ((params.length >= 2) ? params[1] : "true");
420             String ajaxSubmit = ((params.length >= 3) ? params[2] : "true");
421             String successCallback = ((params.length >= 4) ? params[3] : "null");
422 
423             String submitData = "null";
424 
425             if (splitData.length > 1) {
426                 submitData = splitData[1].trim();
427             }
428 
429             methodToCall = StringUtils.remove(methodToCall, "'");
430             methodToCall = StringUtils.remove(methodToCall, "\"");
431 
432             messagePiece = "<a href=\"javascript:void(null)\" onclick=\"submitForm(" +
433                     "'" +
434                     methodToCall +
435                     "'," +
436                     submitData +
437                     "," +
438                     validate +
439                     "," +
440                     ajaxSubmit +
441                     "," +
442                     successCallback +
443                     "); return false;\">";
444         } else {
445             messagePiece = "</a>";
446         }
447 
448         return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
449     }
450 
451     /**
452      * Process a piece of the message that is assumed to have a valid html tag
453      *
454      * @param messagePiece String piece with html tag content
455      * @param currentMessageComponent the state of the current text based message being built
456      * @param view current View
457      * @return currentMessageComponent with the new textual content generated by this method appended to its
458      *         messageText
459      */
460     private static Message processHtmlContent(String messagePiece, Message currentMessageComponent, View view) {
461         //raw html
462         messagePiece = messagePiece.trim();
463 
464         if (StringUtils.startsWithAny(messagePiece, KRADConstants.MessageParsing.UNALLOWED_HTML) || StringUtils
465                 .endsWithAny(messagePiece, KRADConstants.MessageParsing.UNALLOWED_HTML)) {
466             throw new RuntimeException("The following html is not allowed in Messages: " + Arrays.toString(
467                     KRADConstants.MessageParsing.UNALLOWED_HTML));
468         }
469 
470         messagePiece = "<" + messagePiece + ">";
471 
472         return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
473     }
474 }