1 19 20 package org.apache.cayenne.util; 21 22 import java.util.HashMap ; 23 import java.util.Map ; 24 import java.util.StringTokenizer ; 25 26 32 public class NameConverter { 33 34 private static final Map SPECIAL_CHAR_TO_JAVA_MAPPING = new HashMap (); 35 36 static { 37 SPECIAL_CHAR_TO_JAVA_MAPPING.put("#", "pound"); 38 } 39 40 46 public static String javaToUnderscored(String name) { 47 if (name == null) { 48 return null; 49 } 50 51 name = specialCharsToJava(name); 55 56 char charArray[] = name.toCharArray(); 57 StringBuffer buffer = new StringBuffer (); 58 59 for (int i = 0; i < charArray.length; i++) { 60 if ((Character.isUpperCase(charArray[i])) && (i != 0)) { 61 62 char prevChar = charArray[i - 1]; 63 if ((Character.isLowerCase(prevChar))) { 64 buffer.append("_"); 65 } 66 } 67 68 buffer.append(Character.toUpperCase(charArray[i])); 69 } 70 71 return buffer.toString(); 72 } 73 74 81 public static String underscoredToJava(String name, boolean capitalize) { 82 StringTokenizer st = new StringTokenizer (name, "_"); 83 StringBuffer buf = new StringBuffer (); 84 85 boolean first = true; 86 while (st.hasMoreTokens()) { 87 String token = st.nextToken(); 88 89 token = specialCharsToJava(token); 91 92 int len = token.length(); 93 if (len == 0) { 94 continue; 95 } 96 97 boolean hasLowerCase = false; 99 boolean hasUpperCase = false; 100 for (int i = 0; i < len && !(hasUpperCase && hasLowerCase); i++) { 101 if (Character.isUpperCase(token.charAt(i))) { 102 hasUpperCase = true; 103 } 104 else if (Character.isLowerCase(token.charAt(i))) { 105 hasLowerCase = true; 106 } 107 } 108 109 if (hasUpperCase && !hasLowerCase) { 111 token = token.toLowerCase(); 112 } 113 114 if (first) { 115 first = false; 117 if (capitalize) { 118 buf.append(Character.toUpperCase(token.charAt(0))); 119 } 120 else { 121 buf.append(Character.toLowerCase(token.charAt(0))); 122 } 123 } 124 else { 125 buf.append(Character.toUpperCase(token.charAt(0))); 126 } 127 128 if (len > 1) { 129 buf.append(token.substring(1, len)); 130 } 131 } 132 return buf.toString(); 133 } 134 135 138 static String specialCharsToJava(String string) { 139 int len = string.length(); 140 if (len == 0) { 141 return string; 142 } 143 144 StringBuffer buffer = new StringBuffer (len); 145 for (int i = 0; i < len; i++) { 146 147 char c = string.charAt(i); 148 if (Character.isJavaIdentifierPart(c)) { 149 buffer.append(c); 150 } 151 else { 152 Object word = SPECIAL_CHAR_TO_JAVA_MAPPING.get(String.valueOf(c)); 153 buffer.append(word != null ? word : "_"); 154 } 155 } 156 157 return buffer.toString(); 158 } 159 } 160 | Popular Tags |