1 package com.icesoft.faces.webapp.command; 2 3 import com.icesoft.faces.util.DOMUtils; 4 import org.w3c.dom.Element ; 5 6 import java.io.IOException ; 7 import java.io.StringWriter ; 8 import java.io.Writer ; 9 import java.util.Arrays ; 10 import java.util.HashSet ; 11 import java.util.Set ; 12 import java.util.regex.Pattern ; 13 14 public class UpdateElements implements Command { 15 private final static Pattern START_CDATA = Pattern.compile("<\\!\\[CDATA\\["); 16 private final static Pattern END_CDATA = Pattern.compile("\\]\\]>"); 17 private Element [] updates; 18 19 public UpdateElements(Element [] updates) { 20 this.updates = updates; 21 } 22 23 public Command coalesceWith(UpdateElements updateElementsCommand) { 24 Set coallescedUpdates = new HashSet (); 25 Element [] previousUpdates = updateElementsCommand.updates; 26 27 for (int i = 0; i < previousUpdates.length; i++) { 28 Element previousUpdate = previousUpdates[i]; 29 Element selectedUpdate = previousUpdate; 30 for (int j = 0; j < updates.length; j++) { 31 Element update = updates[j]; 32 if (update.getAttribute("id").equals(previousUpdate.getAttribute("id"))) { 33 selectedUpdate = update; 34 break; 35 } 36 } 37 coallescedUpdates.add(selectedUpdate); 38 } 39 coallescedUpdates.addAll(Arrays.asList(updates)); 40 41 return new UpdateElements((Element []) coallescedUpdates.toArray(new Element [coallescedUpdates.size()])); 42 } 43 44 public Command coalesceWith(Command command) { 45 return command.coalesceWith(this); 46 } 47 48 public Command coalesceWith(Macro macro) { 49 return new Macro(macro, this); 50 } 51 52 public Command coalesceWith(Redirect redirect) { 53 return new Macro(redirect, this); 54 } 55 56 public Command coalesceWith(SessionExpired sessionExpired) { 57 return sessionExpired; 58 } 59 60 public Command coalesceWith(SetCookie setCookie) { 61 return new Macro(setCookie, this); 62 } 63 64 public Command coalesceWith(Pong pong) { 65 return new Macro(pong, this); 66 } 67 68 public Command coalesceWith(NOOP noop) { 69 return this; 70 } 71 72 public void serializeTo(Writer writer) throws IOException { 73 writer.write("<updates>"); 74 for (int i = 0; i < updates.length; i++) { 75 Element update = updates[i]; 76 if (update == null) continue; 77 writer.write("<update address=\""); 78 writer.write(update.getAttribute("id")); 79 writer.write("\"><![CDATA["); 80 String content = DOMUtils.nodeToString(update); 81 content = START_CDATA.matcher(content).replaceAll("<!#cdata#"); 82 content = END_CDATA.matcher(content).replaceAll("##>"); 83 writer.write(content); 84 writer.write("]]></update>"); 85 } 86 writer.write("</updates>"); 87 } 88 89 public String toString() { 90 try { 91 StringWriter writer = new StringWriter (); 92 serializeTo(writer); 93 return writer.toString(); 94 } catch (IOException e) { 95 throw new RuntimeException (e); 96 } 97 } 98 } 99 | Popular Tags |