001package io.ebean.util; 002 003public class CamelCaseHelper { 004 005 /** 006 * To underscore from camel case using digits compressed true and force upper case false. 007 */ 008 public static String toUnderscoreFromCamel(String camelCase) { 009 return toUnderscoreFromCamel(camelCase, true, false); 010 } 011 012 /** 013 * Convert and return the string to underscore from camel case. 014 */ 015 public static String toUnderscoreFromCamel(String camelCase, boolean digitsCompressed, boolean forceUpperCase) { 016 017 int lastUpper = -1; 018 StringBuilder sb = new StringBuilder(camelCase.length() + 4); 019 for (int i = 0; i < camelCase.length(); i++) { 020 char c = camelCase.charAt(i); 021 022 if ('_' == c) { 023 // Underscores should just be passed through 024 sb.append(c); 025 lastUpper = i; 026 } else if (Character.isDigit(c)) { 027 if (i > lastUpper + 1 && !digitsCompressed) { 028 sb.append("_"); 029 lastUpper = i; 030 } 031 sb.append(c); 032 033 } else if (Character.isUpperCase(c)) { 034 if (i > lastUpper + 1) { 035 sb.append("_"); 036 } 037 sb.append(Character.toLowerCase(c)); 038 lastUpper = i; 039 040 } else { 041 sb.append(c); 042 } 043 } 044 String ret = sb.toString(); 045 if (forceUpperCase) { 046 ret = ret.toUpperCase(); 047 } 048 return ret; 049 } 050 051 /** 052 * To camel from underscore. 053 * 054 * @param underscore the underscore 055 * @return the string 056 */ 057 public static String toCamelFromUnderscore(String underscore) { 058 059 String[] vals = underscore.split("_"); 060 if (vals.length == 1) { 061 return isUpperCase(underscore) ? underscore.toLowerCase() : underscore; 062 } 063 064 StringBuilder result = new StringBuilder(); 065 for (int i = 0; i < vals.length; i++) { 066 String lower = vals[i].toLowerCase(); 067 if (i > 0) { 068 char c = Character.toUpperCase(lower.charAt(0)); 069 result.append(c); 070 result.append(lower.substring(1)); 071 } else { 072 result.append(lower); 073 } 074 } 075 076 return result.toString(); 077 } 078 079 private static boolean isUpperCase(String underscore) { 080 for (int i = 0; i < underscore.length(); i++) { 081 if (Character.isLowerCase(underscore.charAt(i))) { 082 return false; 083 } 084 } 085 return true; 086 } 087}