1 4 5 42 43 package org.apache.cocoon.faces.samples.carstore; 44 45 46 import javax.faces.application.FacesMessage; 47 import javax.faces.component.UIComponent; 48 import javax.faces.context.FacesContext; 49 import javax.faces.convert.Converter; 50 import javax.faces.convert.ConverterException; 51 52 59 public class CreditCardConverter implements Converter { 60 61 68 public static final String CONVERSION_ERROR_MESSAGE_ID = 69 "carstore.Conversion_Error"; 70 71 72 76 public Object getAsObject(FacesContext context, UIComponent component, 77 String newValue) throws ConverterException { 78 79 String convertedValue = null; 80 if (newValue == null) { 81 return newValue; 82 } 83 convertedValue = newValue.trim(); 86 if (((convertedValue.indexOf("-")) != -1) || 87 ((convertedValue.indexOf(" ")) != -1)) { 88 char[] input = convertedValue.toCharArray(); 89 StringBuffer buffer = new StringBuffer (50); 90 for (int i = 0; i < input.length; ++i) { 91 if (input[i] == '-' || input[i] == ' ') { 92 continue; 93 } else { 94 buffer.append(input[i]); 95 } 96 } 97 convertedValue = buffer.toString(); 98 } 99 return convertedValue; 101 } 102 103 104 109 public String getAsString(FacesContext context, UIComponent component, 110 Object value) throws ConverterException { 111 112 String inputVal = null; 113 if (value == null) { 114 return null; 115 } 116 try { 118 inputVal = (String ) value; 119 } catch (ClassCastException ce) { 120 FacesMessage errMsg = MessageFactory.getMessage( 121 CONVERSION_ERROR_MESSAGE_ID, 122 (new Object []{value, inputVal})); 123 throw new ConverterException(errMsg.getSummary()); 124 } 125 126 char[] input = inputVal.toCharArray(); 129 StringBuffer buffer = new StringBuffer (50); 130 for (int i = 0; i < input.length; ++i) { 131 if ((i % 4) == 0 && i != 0) { 132 if (input[i] != ' ' || input[i] != '-') { 133 buffer.append(" "); 134 } else if (input[i] == '-') { 136 buffer.append(" "); 137 } 138 } 139 buffer.append(input[i]); 140 } 141 String convertedValue = buffer.toString(); 142 return convertedValue; 144 } 145 } 146 | Popular Tags |