среда, 19 июня 2013 г.

Dynamic elements replacement in GWT

    Let's say you want to replace all email addresses from string to some clickable element or maybe add custom handler. I'll show you a way how to do it. 
     For the purpose of this example, we will assume that server side response to the client some information that contains different email addresses. Something like this:
&nbsp;&nbsp;<b>Main requirements:</b><br/>Expertise in Java, Spring Framework, Hibernate, JMS, Enterprise Integration Platforms.<br/>Experience with GWT, JavaScript, JQuery.<br/>Strong object oriented programming concepts: Ability to develop flexible and scalable concept.<br/>Strong understanding of GoF Design Patterns, J2EE Patterns and anti-patterns.<br/>&nbsp;&nbsp;<b>Nice to Have:</b><br/>Experience working with coherent, terracotta technology.<br/>Experience in Subversion, Maven.<br/>Outstanding analytical and communication skills.<br/><br/>Unix/Linux Experience.<br/>Client contact details: first@gmail.com<br/>Email your resume in Word to: second@gmail.com
     But we need to hide the addresses from the UI (so that they do not appear in plain text within HTML) and replace to anchors with text "Send an email message". 
     Next I will show the code in chunks, with a bit of comments for each chunk.
The first things we should do its write a method that replaces each email address that matches the regular expression.
  1. /**
  2. * How to extract all emails from string and replace them.
  3. * Search and replacement e-mails.
  4. *
  5. * @author Dmitry Nikolaenko
  6. *
  7. */
  8. public final class StringUtils {
  9.     public static final String EMAIL_REGEXP =
  10.             "([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})";
  11.     
  12.     /**
  13.      * Only constructed by ourselves. Class contains only static methods.
  14.      */
  15.     private StringUtils() {}
  16.  
  17.     /**
  18.      * Replaces each email that matches the regular expression.
  19.      *
  20.      * @param text the <code>String</code> that is contained required text to handle
  21.      * @return the resulting <tt>String</tt>
  22.      */
  23.     public static String replaceEmail(final String text) {
  24.         // array without any emails
  25.         String[] words = text.split(EMAIL_REGEXP);
  26.  
  27.         String emails = text;
  28.         String result = text;
  29.  
  30.         if (words.length > 1) {
  31.             // gather only emails in one string
  32.             for (String word : words) {
  33.                 if (!word.trim().isEmpty()) {
  34.                     emails = emails.replace(word, " ").trim();
  35.                 }
  36.             }
  37.  
  38.             if (!emails.isEmpty()) {
  39.                 // execute replacement for pattern
  40.                 for (String word : emails.split(" ")) {
  41.                     if (text.contains(word)) {
  42.                         result = result.replaceAll(word, constructReplacement(word));
  43.                     }
  44.                 }
  45.             }
  46.         }
  47.  
  48.         return result;
  49.     }
  50.  
  51.     private static String constructReplacement(final String email) {
  52.         // String#format() doesn't work in GWT
  53.         //return String.format("<a href=\"mailto:%s\">%s</a>", email, email);
  54.         return new StringBuilder("<a href=mailto:").append(email).
  55.                   append(">").append("Send email").append("</a>").toString();
  56.     }
  57. }
     Next step we will find all <a></a> elements and convert them into GWT#anchors.
  1. RootPanel.get().add(new Button("Change click handler for emails") {{
  2.     addClickHandler(new ClickHandler() {
  3.         @Override
  4.         public void onClick(ClickEvent event) {
  5.             NodeList<Element> anchors = html.getElement().getElementsByTagName("a");
  6.             for (int i = 0; i < anchors.getLength(); i++) {
  7.                 Element anchor = anchors.getItem(i);
  8.                 final Anchor email = new Anchor(anchor.getInnerHTML());
  9.                 email.addClickHandler(new ClickHandler() {
  10.                     @Override
  11.                     public void onClick(ClickEvent event) {
  12.                         Window.alert("Send an email message");
  13.                     }
  14.                 });
  15.                 html.addAndReplaceElement(email, anchor);
  16.             }
  17.         }
  18.     });
  19. }});     
Before(reply from server side):

     After(after data processing):

     Here's a link to the source code.

Комментариев нет:

Отправить комментарий