proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/core/SensitiveWord.java
SensitiveWord
innerSensitiveWords
class SensitiveWord extends AbstractSensitiveWord { /** * 0.3.2 */ private static final ISensitiveWord INSTANCE = new SensitiveWord(); public static ISensitiveWord getInstance() { return INSTANCE; } @Override protected List<IWordResult> doFindAll(String string, IWordContext context) { return innerSensitiveWords(string, WordValidModeEnum.FAIL_OVER, context); } /** * 获取敏感词列表 * * @param text 文本 * @param modeEnum 模式 * @return 结果列表 * @since 0.0.1 */ private List<IWordResult> innerSensitiveWords(final String text, final WordValidModeEnum modeEnum, final IWordContext context) {<FILL_FUNCTION_BODY>} }
//1. 是否存在敏感词,如果比存在,直接返回空列表 final IWordCheck sensitiveCheck = context.sensitiveCheck(); List<IWordResult> resultList = Guavas.newArrayList(); //TODO: 这里拆分为2个部分,从而保障性能。但是要注意处理下标的问题。 //1. 原始的敏感词部分 //2. email/url/num 的单独一次遍历处理。 final Map<Character, Character> characterCharacterMap = InnerWordFormatUtils.formatCharsMapping(text, context); final InnerSensitiveWordContext checkContext = InnerSensitiveWordContext.newInstance() .originalText(text) .wordContext(context) .modeEnum(WordValidModeEnum.FAIL_OVER) .formatCharMapping(characterCharacterMap); final IWordResultCondition wordResultCondition = context.wordResultCondition(); for (int i = 0; i < text.length(); i++) { WordCheckResult checkResult = sensitiveCheck.sensitiveCheck(i, checkContext); // 命中 int wordLength = checkResult.index(); if (wordLength > 0) { // 保存敏感词 WordResult wordResult = WordResult.newInstance() .startIndex(i) .endIndex(i+wordLength) .type(checkResult.type()); //v0.13.0 添加判断 if(wordResultCondition.match(wordResult, text, modeEnum, context)) { resultList.add(wordResult); } // 快速返回 if (WordValidModeEnum.FAIL_FAST.equals(modeEnum)) { break; } // 增加 i 的步长 // 为什么要-1,因为默认就会自增1 // TODO: 这里可以根据字符串匹配算法优化。 i += wordLength - 1; } } return resultList;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/allow/WordAllowInit.java
WordAllowInit
allow
class WordAllowInit implements IWordAllow { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordAllow> pipeline); @Override public List<String> allow() {<FILL_FUNCTION_BODY>} }
Pipeline<IWordAllow> pipeline = new DefaultPipeline<>(); this.init(pipeline); List<String> results = new ArrayList<>(); List<IWordAllow> wordAllows = pipeline.list(); for (IWordAllow wordAllow : wordAllows) { List<String> allowList = wordAllow.allow(); results.addAll(allowList); } return results;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/allow/WordAllows.java
WordAllows
init
class WordAllows { private WordAllows(){} /** * 责任链 * @param wordAllow 允许 * @param others 其他 * @return 结果 * @since 0.0.13 */ public static IWordAllow chains(final IWordAllow wordAllow, final IWordAllow... others) { return new WordAllowInit() { @Override protected void init(Pipeline<IWordAllow> pipeline) {<FILL_FUNCTION_BODY>} }; } /** * 系统实现 * @return 结果 * @since 0.0.13 */ public static IWordAllow defaults() { return WordAllowSystem.getInstance(); } }
pipeline.addLast(wordAllow); if(ArrayUtil.isNotEmpty(others)) { for(IWordAllow other : others) { pipeline.addLast(other); } }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/AbstractConditionWordCheck.java
AbstractConditionWordCheck
getActualLength
class AbstractConditionWordCheck extends AbstractWordCheck { /** * 当前字符串是否符合规范 * @param mappingChar 当前字符 * @param index 下标 * @param checkContext 校验文本 * @return 结果 * @since 0.3.2 */ protected abstract boolean isCharCondition(char mappingChar, int index, InnerSensitiveWordContext checkContext); /** * 这里指定一个阈值条件 * @param index 当前下标 * @param stringBuilder 缓存 * @param checkContext 上下文 * @return 是否满足条件 * @since 0.3.2 */ protected abstract boolean isStringCondition(int index, final StringBuilder stringBuilder, InnerSensitiveWordContext checkContext); @Override protected int getActualLength(int beginIndex, InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
final String txt = checkContext.originalText(); final IWordContext context = checkContext.wordContext(); final Map<Character, Character> formatCharMapping = checkContext.formatCharMapping(); int actualLength = 0; // 采用 ThreadLocal 应该可以提升性能,减少对象的创建。 StringBuilder stringBuilder = new StringBuilder(); int currentIx = 0; for(int i = beginIndex; i < txt.length(); i++) { currentIx = i; char currentChar = txt.charAt(i); // 映射处理 char mappingChar = formatCharMapping.get(currentChar); // 符合条件 boolean currentCondition = isCharCondition(mappingChar, i, checkContext); //4 个场景 if(currentCondition) { stringBuilder.append(currentChar); } else { break; } } // 匹配 if(isStringCondition(currentIx, stringBuilder, checkContext)) { actualLength = stringBuilder.length(); } return actualLength;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/AbstractWordCheck.java
AbstractWordCheck
sensitiveCheck
class AbstractWordCheck implements IWordCheck { /** * 获取校验类 * @return 类 * @since 0.3.2 */ protected abstract Class<? extends IWordCheck> getSensitiveCheckClass(); /** * 获取确切的长度 * @param beginIndex 开始 * @param checkContext 上下文 * @return 长度 * @since 0.4.0 */ protected abstract int getActualLength(int beginIndex, final InnerSensitiveWordContext checkContext); /** * 获取类别 * @return 类别 * @since 0.14.0 */ protected abstract String getType(); @Override public WordCheckResult sensitiveCheck(int beginIndex, final InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
Class<? extends IWordCheck> clazz = getSensitiveCheckClass(); final String txt = checkContext.originalText(); if(StringUtil.isEmpty(txt)) { return WordCheckResult.newInstance() .index(0) .type(getType()) .checkClass(clazz); } int actualLength = getActualLength(beginIndex, checkContext); return WordCheckResult.newInstance() .index(actualLength) .type(getType()) .checkClass(clazz);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckEmail.java
WordCheckEmail
isStringCondition
class WordCheckEmail extends AbstractConditionWordCheck { /** * @since 0.3.0 */ private static final IWordCheck INSTANCE = new WordCheckEmail(); public static IWordCheck getInstance() { return INSTANCE; } @Override protected Class<? extends IWordCheck> getSensitiveCheckClass() { return WordCheckEmail.class; } @Override protected String getType() { return WordTypeEnum.EMAIL.getCode(); } @Override protected boolean isCharCondition(char mappingChar, int index, InnerSensitiveWordContext checkContext) { return CharUtil.isEmilChar(mappingChar); } @Override protected boolean isStringCondition(int index, StringBuilder stringBuilder, InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
int bufferLen = stringBuilder.length(); //x@a.cn if(bufferLen < 6) { return false; } if(bufferLen > WordConst.MAX_EMAIL_LEN) { return false; } String string = stringBuilder.toString(); return RegexUtil.isEmail(string);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckInit.java
WordCheckInit
sensitiveCheck
class WordCheckInit implements IWordCheck { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordCheck> pipeline); @Override public WordCheckResult sensitiveCheck(final int beginIndex, final InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
Pipeline<IWordCheck> pipeline = new DefaultPipeline<>(); this.init(pipeline); List<IWordCheck> sensitiveChecks = pipeline.list(); // 循环调用 for(IWordCheck sensitiveCheck : sensitiveChecks) { WordCheckResult result = sensitiveCheck.sensitiveCheck(beginIndex, checkContext); if(result.index() > 0) { return result; } } // 这里直接进行正则表达式相关的调用。 // 默认返回 0 return WordCheckNone.getNoneResult();
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckResult.java
WordCheckResult
toString
class WordCheckResult { /** * 下标 * @since 0.0.12 */ private int index; /** * 检测类 * @since 0.0.12 */ private Class<? extends IWordCheck> checkClass; /** * 单词类别 * @since 0.14.0 */ private String type; private WordCheckResult(){} public static WordCheckResult newInstance() { return new WordCheckResult(); } public int index() { return index; } public WordCheckResult index(int index) { this.index = index; return this; } public Class<? extends IWordCheck> checkClass() { return checkClass; } public WordCheckResult checkClass(Class<? extends IWordCheck> checkClass) { this.checkClass = checkClass; return this; } public String type() { return type; } public WordCheckResult type(String type) { this.type = type; return this; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "WordCheckResult{" + "index=" + index + ", checkClass=" + checkClass + ", type='" + type + '\'' + '}';
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckUrl.java
WordCheckUrl
isStringCondition
class WordCheckUrl extends AbstractConditionWordCheck { /** * @since 0.3.0 */ private static final IWordCheck INSTANCE = new WordCheckUrl(); public static IWordCheck getInstance() { return INSTANCE; } @Override protected Class<? extends IWordCheck> getSensitiveCheckClass() { return WordCheckUrl.class; } @Override protected String getType() { return WordTypeEnum.URL.getCode(); } @Override protected boolean isCharCondition(char mappingChar, int index, InnerSensitiveWordContext checkContext) { return CharUtil.isWebSiteChar(mappingChar); } @Override protected boolean isStringCondition(int index, StringBuilder stringBuilder, InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
int bufferLen = stringBuilder.length(); //a.cn if(bufferLen < 4) { return false; } if(bufferLen > WordConst.MAX_WEB_SITE_LEN) { return false; } String string = stringBuilder.toString(); return RegexUtil.isWebSite(string);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckWord.java
WordCheckWord
getActualLength
class WordCheckWord extends AbstractWordCheck { /** * @since 0.3.0 */ private static final IWordCheck INSTANCE = new WordCheckWord(); public static IWordCheck getInstance() { return INSTANCE; } @Override protected Class<? extends IWordCheck> getSensitiveCheckClass() { return WordCheckWord.class; } @Override protected int getActualLength(int beginIndex, InnerSensitiveWordContext innerContext) {<FILL_FUNCTION_BODY>} @Override protected String getType() { return WordTypeEnum.WORD.getCode(); } }
final String txt = innerContext.originalText(); final Map<Character, Character> formatCharMapping = innerContext.formatCharMapping(); final WordValidModeEnum wordValidModeEnum = innerContext.modeEnum(); final IWordContext context = innerContext.wordContext(); // 采用 ThreadLocal 应该可以提升性能,减少对象的创建。 int actualLength = 0; final IWordData wordData = context.wordData(); // 前一个条件 StringBuilder stringBuilder = new StringBuilder(); char[] rawChars = txt.toCharArray(); final ISensitiveWordCharIgnore wordCharIgnore = context.charIgnore(); int tempLen = 0; for(int i = beginIndex; i < rawChars.length; i++) { // 判断是否跳过? if(wordCharIgnore.ignore(i, rawChars, innerContext)) { tempLen++; continue; } // 映射处理 final char currentChar = rawChars[i]; char mappingChar = formatCharMapping.get(currentChar); stringBuilder.append(mappingChar); tempLen++; // 判断是否存在 WordContainsTypeEnum wordContainsTypeEnum = wordData.contains(stringBuilder, innerContext); if(WordContainsTypeEnum.CONTAINS_END.equals(wordContainsTypeEnum)) { actualLength = tempLen; // 是否遍历全部匹配的模式 if(WordValidModeEnum.FAIL_FAST.equals(wordValidModeEnum)) { break; } } // 如果不包含,则直接返回。后续遍历无意义 if(WordContainsTypeEnum.NOT_FOUND.equals(wordContainsTypeEnum)) { break; } } return actualLength;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordChecks.java
WordChecks
chains
class WordChecks { private WordChecks(){} /** * 初始化敏感检测策略 * @param context 上下文 * * @return 实现 * @since 0.3.0 */ public static IWordCheck initSensitiveCheck(final IWordContext context) { List<IWordCheck> sensitiveCheckList = new ArrayList<>(); if(context.enableWordCheck()) { sensitiveCheckList.add(WordChecks.word()); } if(context.enableNumCheck()) { sensitiveCheckList.add(WordChecks.num()); } if(context.enableEmailCheck()) { sensitiveCheckList.add(WordChecks.email()); } if(context.enableUrlCheck()) { sensitiveCheckList.add(WordChecks.url()); } return WordChecks.chains(sensitiveCheckList); } public static IWordCheck chains(final IWordCheck... sensitiveChecks) { if (ArrayUtil.isEmpty(sensitiveChecks)){ return none(); } return new WordCheckInit() { @Override protected void init(Pipeline<IWordCheck> pipeline) { for(IWordCheck check : sensitiveChecks) { pipeline.addLast(check); } } }; } public static IWordCheck chains(final Collection<IWordCheck> sensitiveChecks) {<FILL_FUNCTION_BODY>} public static IWordCheck email() { return WordCheckEmail.getInstance(); } public static IWordCheck num() { return WordCheckNum.getInstance(); } public static IWordCheck url() { return WordCheckUrl.getInstance(); } public static IWordCheck word() { return WordCheckWord.getInstance(); } public static IWordCheck none() { return WordCheckNone.getInstance(); } }
if (CollectionUtil.isEmpty(sensitiveChecks)){ return none(); } return new WordCheckInit() { @Override protected void init(Pipeline<IWordCheck> pipeline) { for(IWordCheck check : sensitiveChecks) { pipeline.addLast(check); } } };
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/combine/allowdeny/AbstractWordAllowDenyCombine.java
AbstractWordAllowDenyCombine
getActualDenyList
class AbstractWordAllowDenyCombine implements IWordAllowDenyCombine { protected abstract Collection<String> doGetActualDenyList(List<String> allowList, List<String> denyList, IWordContext context); @Override public Collection<String> getActualDenyList(IWordAllow wordAllow, IWordDeny wordDeny, IWordContext context) {<FILL_FUNCTION_BODY>} }
List<String> allowList = wordAllow.allow(); List<String> denyList = wordDeny.deny(); List<String> formatAllowList = InnerWordFormatUtils.formatWordList(allowList, context); List<String> formatDenyList = InnerWordFormatUtils.formatWordList(denyList, context); if (CollectionUtil.isEmpty(formatDenyList)) { return Collections.emptyList(); } if (CollectionUtil.isEmpty(formatAllowList)) { return formatDenyList; } return doGetActualDenyList(formatAllowList, formatDenyList, context);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/combine/allowdeny/WordAllowDenyCombine.java
WordAllowDenyCombine
doGetActualDenyList
class WordAllowDenyCombine extends AbstractWordAllowDenyCombine{ @Override protected Collection<String> doGetActualDenyList(List<String> allowList, List<String> denyList, IWordContext context) {<FILL_FUNCTION_BODY>} }
Set<String> resultSet = new HashSet<>(denyList.size()); // O(1) Set<String> allowSet = new HashSet<>(allowList); for(String deny : denyList) { if(allowSet.contains(deny)) { continue; } resultSet.add(deny); } return resultSet;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/combine/check/WordCheckCombine.java
WordCheckCombine
getWordCheckList
class WordCheckCombine extends AbstractWordCheckCombine { @Override protected List<IWordCheck> getWordCheckList(IWordContext context) {<FILL_FUNCTION_BODY>} }
List<IWordCheck> wordCheckList = new ArrayList<>(); if(context.enableWordCheck()) { wordCheckList.add(WordChecks.word()); } if(context.enableNumCheck()) { wordCheckList.add(WordChecks.num()); } if(context.enableEmailCheck()) { wordCheckList.add(WordChecks.email()); } if(context.enableUrlCheck()) { wordCheckList.add(WordChecks.url()); } return wordCheckList;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/combine/format/WordFormatCombine.java
WordFormatCombine
getWordFormatList
class WordFormatCombine extends AbstractWordFormatCombine { @Override protected List<IWordFormat> getWordFormatList(IWordContext context) {<FILL_FUNCTION_BODY>} }
List<IWordFormat> charFormats = Guavas.newArrayList(); if(context.ignoreEnglishStyle()) { charFormats.add(WordFormats.ignoreEnglishStyle()); } if(context.ignoreCase()) { charFormats.add(WordFormats.ignoreCase()); } if(context.ignoreWidth()) { charFormats.add(WordFormats.ignoreWidth()); } if(context.ignoreNumStyle()) { charFormats.add(WordFormats.ignoreNumStyle()); } if(context.ignoreChineseStyle()) { charFormats.add(WordFormats.ignoreChineseStyle()); } return charFormats;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/data/AbstractWordData.java
AbstractWordData
contains
class AbstractWordData implements IWordData { /** * 是否包含 * @param stringBuilder 字符 * @param innerContext 上下文 * @return 结果 */ protected abstract WordContainsTypeEnum doContains(StringBuilder stringBuilder, InnerSensitiveWordContext innerContext); /** * 初始化 * @param collection 数据 */ protected abstract void doInitWordData(Collection<String> collection); @Override public void initWordData(Collection<String> collection) { //1. 预留 this.doInitWordData(collection); } @Override public WordContainsTypeEnum contains(StringBuilder stringBuilder, InnerSensitiveWordContext innerContext) {<FILL_FUNCTION_BODY>} }
if(stringBuilder == null || stringBuilder.length() <= 0) { return WordContainsTypeEnum.NOT_FOUND; } return doContains(stringBuilder, innerContext);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/data/WordDataHashMap.java
WordDataHashMap
getNowMap
class WordDataHashMap extends AbstractWordData { /** * 脱敏单词 map * * @since 0.0.1 */ private Map innerWordMap; /** * 读取敏感词库,将敏感词放入HashSet中,构建一个DFA算法模型: * * @param collection 敏感词库集合 * @since 0.0.1 * <p> * 使用对象代码 map 的这种一直递归。 * 参考资料:https://www.cnblogs.com/AlanLee/p/5329555.html * https://blog.csdn.net/chenssy/article/details/26961957 */ @Override @SuppressWarnings("unchecked") public synchronized void doInitWordData(Collection<String> collection) { // 避免扩容带来的消耗 Map newInnerWordMap = new HashMap(collection.size()); for (String key : collection) { if (StringUtil.isEmpty(key)) { continue; } // 用来按照相应的格式保存敏感词库数据 char[] chars = key.toCharArray(); final int size = chars.length; // 每一个新词的循环,直接将结果设置为当前 map,所有变化都会体现在结果的 map 中 Map currentMap = newInnerWordMap; for (int i = 0; i < size; i++) { // 截取敏感词当中的字,在敏感词库中字为HashMap对象的Key键值 char charKey = chars[i]; // 如果集合存在 Object wordMap = currentMap.get(charKey); // 如果集合存在 if (ObjectUtil.isNotNull(wordMap)) { // 直接将获取到的 map 当前当前 map 进行继续的操作 currentMap = (Map) wordMap; } else { //不存在则,则构建一个新的map,同时将isEnd设置为0,因为他不是最后一 Map<String, Boolean> newWordMap = new HashMap<>(8); newWordMap.put(WordConst.IS_END, false); // 将新的节点放入当前 map 中 currentMap.put(charKey, newWordMap); // 将新节点设置为当前节点,方便下一次节点的循环。 currentMap = newWordMap; } } // 判断是否为最后一个,添加是否结束的标识。 currentMap.put(WordConst.IS_END, true); } // 最后更新为新的 map,保证更新过程中旧的数据可用 this.innerWordMap = newInnerWordMap; } /** * 是否包含 * (1)直接遍历所有 * (2)如果遇到,则直接返回 true * * @param stringBuilder 字符串 * @param innerContext 内部上下文 * @return 是否包含 * @since 0.0.1 */ @Override public WordContainsTypeEnum doContains(final StringBuilder stringBuilder, final InnerSensitiveWordContext innerContext) { return innerContainsSensitive(stringBuilder, innerContext); } private WordContainsTypeEnum innerContainsSensitive(StringBuilder stringBuilder, final InnerSensitiveWordContext innerContext) { // 初始化为当前的 map Map nowMap = this.innerWordMap; // 记录敏感词的长度 final int len = stringBuilder.length(); for (int i = 0; i < len; i++) { // 获取当前的 map 信息 nowMap = getNowMap(nowMap, i, stringBuilder, innerContext); // 如果不为空,则判断是否为结尾。 if (ObjectUtil.isNull(nowMap)) { return WordContainsTypeEnum.NOT_FOUND; } } // 是否为结尾,便于快速失败 boolean isEnd = isEnd(nowMap); if(isEnd) { return WordContainsTypeEnum.CONTAINS_END; } return WordContainsTypeEnum.CONTAINS_PREFIX; } /** * 判断是否结束 * BUG-FIX: 避免出现敏感词库中没有的文字。 * @param map map 信息 * @return 是否结束 * @since 0.0.9 */ private static boolean isEnd(final Map map) { if(ObjectUtil.isNull(map)) { return false; } Object value = map.get(WordConst.IS_END); if(ObjectUtil.isNull(value)) { return false; } return (boolean)value; } /** * 获取当前的 Map * @param nowMap 原始的当前 map * @param index 下标 * @param stringBuilder 文本缓存 * @param sensitiveContext 上下文 * @return 实际的当前 map * @since 0.0.7 */ private Map getNowMap(Map nowMap, final int index, final StringBuilder stringBuilder, final InnerSensitiveWordContext sensitiveContext) {<FILL_FUNCTION_BODY>} }
final IWordContext context = sensitiveContext.wordContext(); // 这里的 char 已经是统一格式化之后的,所以可以不用再次格式化。 char mappingChar = stringBuilder.charAt(index); // 这里做一次重复词的处理 //TODO: 这里可以优化,是否获取一次。 Map currentMap = (Map) nowMap.get(mappingChar); // 启用忽略重复&当前下标不是第一个 if(context.ignoreRepeat() && index > 0) { char preMappingChar = stringBuilder.charAt(index-1); // 直接赋值为上一个 map if(preMappingChar == mappingChar) { currentMap = nowMap; } } return currentMap;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/data/WordDataTree.java
WordDataTree
initWordData
class WordDataTree implements IWordData { /** * 根节点 */ private WordDataTreeNode root; @Override public synchronized void initWordData(Collection<String> collection) {<FILL_FUNCTION_BODY>} @Override public WordContainsTypeEnum contains(StringBuilder stringBuilder, InnerSensitiveWordContext innerContext) { WordDataTreeNode nowNode = root; int len = stringBuilder.length(); for(int i = 0; i < len; i++) { // 获取当前的 map 信息 nowNode = getNowMap(nowNode, i, stringBuilder, innerContext); // 如果不为空,则判断是否为结尾。 if (ObjectUtil.isNull(nowNode)) { return WordContainsTypeEnum.NOT_FOUND; } } if(nowNode.end()) { return WordContainsTypeEnum.CONTAINS_END; } return WordContainsTypeEnum.CONTAINS_PREFIX; } /** * 获取当前的 Map * @param nowNode 当前节点 * @param index 下标 * @param stringBuilder 文本缓存 * @param sensitiveContext 上下文 * @return 实际的当前 map * @since 0.0.7 */ private WordDataTreeNode getNowMap(WordDataTreeNode nowNode, final int index, final StringBuilder stringBuilder, final InnerSensitiveWordContext sensitiveContext) { final IWordContext context = sensitiveContext.wordContext(); // 这里的 char 已经是统一格式化之后的,所以可以不用再次格式化。 char mappingChar = stringBuilder.charAt(index); // 这里做一次重复词的处理 WordDataTreeNode currentMap = nowNode.getSubNode(mappingChar); // 启用忽略重复&当前下标不是第一个 if(context.ignoreRepeat() && index > 0) { char preMappingChar = stringBuilder.charAt(index-1); // 直接赋值为上一个 map if(preMappingChar == mappingChar) { currentMap = nowNode; } } return currentMap; } }
WordDataTreeNode newRoot = new WordDataTreeNode(); for(String word : collection) { if(StringUtil.isEmpty(word)) { continue; } WordDataTreeNode tempNode = newRoot; char[] chars = word.toCharArray(); for (char c : chars) { // 获取子节点 WordDataTreeNode subNode = tempNode.getSubNode(c); if (subNode == null) { subNode = new WordDataTreeNode(); // 加入新的子节点 tempNode.addSubNode(c, subNode); } // 临时节点指向子节点,进入下一次循环 tempNode = subNode; } // 设置结束标识(循环结束,设置一次即可) tempNode.end(true); } // 初始化完成才做替换 this.root = newRoot;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/data/WordDataTreeNode.java
WordDataTreeNode
getSubNode
class WordDataTreeNode { /** * 关键词结束标识 */ private boolean end; /** * 子节点(key是下级字符,value是下级节点) */ private Map<Character, WordDataTreeNode> subNodeMap; public boolean end() { return end; } public WordDataTreeNode end(boolean end) { this.end = end; return this; } public WordDataTreeNode getSubNode(final char c) {<FILL_FUNCTION_BODY>} public WordDataTreeNode addSubNode(char c, WordDataTreeNode subNode) { if(this.subNodeMap == null) { subNodeMap = new HashMap<>(); } subNodeMap.put(c, subNode); return this; } }
if(subNodeMap == null) { return null; } return subNodeMap.get(c);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/deny/WordDenyInit.java
WordDenyInit
deny
class WordDenyInit implements IWordDeny { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordDeny> pipeline); @Override public List<String> deny() {<FILL_FUNCTION_BODY>} }
Pipeline<IWordDeny> pipeline = new DefaultPipeline<>(); this.init(pipeline); List<String> results = new ArrayList<>(); List<IWordDeny> wordDenies = pipeline.list(); for (IWordDeny wordDeny : wordDenies) { List<String> denyList = wordDeny.deny(); results.addAll(denyList); } return results;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/deny/WordDenys.java
WordDenys
chains
class WordDenys { private WordDenys(){} /** * 责任链 * @param wordDeny 拒绝 * @param others 其他 * @return 结果 * @since 0.0.13 */ public static IWordDeny chains(final IWordDeny wordDeny, final IWordDeny... others) {<FILL_FUNCTION_BODY>} /** * 系统实现 * @return 结果 * @since 0.0.13 */ public static IWordDeny defaults() { return WordDenySystem.getInstance(); } }
return new WordDenyInit() { @Override protected void init(Pipeline<IWordDeny> pipeline) { pipeline.addLast(wordDeny); if(ArrayUtil.isNotEmpty(others)) { for(IWordDeny other : others) { pipeline.addLast(other); } } } };
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/format/WordFormatIgnoreChineseStyle.java
WordFormatIgnoreChineseStyle
format
class WordFormatIgnoreChineseStyle implements IWordFormat { private static final IWordFormat INSTANCE = new WordFormatIgnoreChineseStyle(); public static IWordFormat getInstance() { return INSTANCE; } @Override public char format(char original, IWordContext context) {<FILL_FUNCTION_BODY>} }
List<String> mappingList = ZhConverterUtil.toSimple(original); if(CollectionUtil.isEmpty(mappingList)) { return original; } return mappingList.get(0).charAt(0);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/format/WordFormatInit.java
WordFormatInit
format
class WordFormatInit implements IWordFormat { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordFormat> pipeline); @Override public char format(char original, IWordContext context) {<FILL_FUNCTION_BODY>} }
Pipeline<IWordFormat> pipeline = new DefaultPipeline<>(); init(pipeline); char result = original; // 循环执行 List<IWordFormat> charFormats = pipeline.list(); for(IWordFormat charFormat : charFormats) { result = charFormat.format(result, context); } return result;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/format/WordFormats.java
WordFormats
chains
class WordFormats { private WordFormats(){} /** * 链式 * @param charFormats 列表 * @return 结果 */ public static IWordFormat chains(final IWordFormat... charFormats) { if(ArrayUtil.isEmpty(charFormats)) { return none(); } return new WordFormatInit() { @Override protected void init(Pipeline<IWordFormat> pipeline) { for(IWordFormat charFormat : charFormats) { pipeline.addLast(charFormat); } } }; } /** * 链式 * @param charFormats 列表 * @return 结果 */ public static IWordFormat chains(final Collection<IWordFormat> charFormats) {<FILL_FUNCTION_BODY>} public static IWordFormat none() { return WordFormatNone.getInstance(); } public static IWordFormat ignoreCase() { return WordFormatIgnoreCase.getInstance(); } public static IWordFormat ignoreEnglishStyle() { return WordFormatIgnoreEnglishStyle.getInstance(); } public static IWordFormat ignoreChineseStyle() { return WordFormatIgnoreChineseStyle.getInstance(); } public static IWordFormat ignoreNumStyle() { return WordFormatIgnoreNumStyle.getInstance(); } public static IWordFormat ignoreWidth() { return WordFormatIgnoreWidth.getInstance(); } }
if(CollectionUtil.isEmpty(charFormats)) { return none(); } return new WordFormatInit() { @Override protected void init(Pipeline<IWordFormat> pipeline) { for(IWordFormat charFormat : charFormats) { pipeline.addLast(charFormat); } } };
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/replace/WordReplaceChar.java
WordReplaceChar
replace
class WordReplaceChar implements IWordReplace { /** * 替换的字符 * @since 0.3.0 */ private final char replaceChar; public WordReplaceChar(char replaceChar) { this.replaceChar = replaceChar; } public WordReplaceChar() { this(CharConst.STAR); } @Override public void replace(StringBuilder stringBuilder, final char[] rawChars, IWordResult wordResult, IWordContext wordContext) {<FILL_FUNCTION_BODY>} }
int wordLen = wordResult.endIndex() - wordResult.startIndex(); for(int i = 0; i < wordLen; i++) { stringBuilder.append(replaceChar); }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/AbstractWordResultHandler.java
AbstractWordResultHandler
handle
class AbstractWordResultHandler<R> implements IWordResultHandler<R> { protected abstract R doHandle(IWordResult wordResult, IWordContext wordContext, String originalText); @Override public R handle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>} }
if(wordResult == null) { return null; } return doHandle(wordResult, wordContext, originalText);
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordResult.java
WordResult
toString
class WordResult implements IWordResult { private int startIndex; private int endIndex; /** * 词类别 * @since 0.14.0 */ private String type; private WordResult(){} public static WordResult newInstance() { return new WordResult(); } @Override public int startIndex() { return startIndex; } public WordResult startIndex(int startIndex) { this.startIndex = startIndex; return this; } @Override public int endIndex() { return endIndex; } public WordResult endIndex(int endIndex) { this.endIndex = endIndex; return this; } @Override public String type() { return type; } public WordResult type(String type) { this.type = type; return this; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "WordResult{" + "startIndex=" + startIndex + ", endIndex=" + endIndex + ", type='" + type + '\'' + '}';
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordResultHandlerWordTags.java
WordResultHandlerWordTags
doHandle
class WordResultHandlerWordTags extends AbstractWordResultHandler<WordTagsDto> { @Override protected WordTagsDto doHandle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>} }
// 截取 String word = InnerWordCharUtils.getString(originalText.toCharArray(), wordResult); // 标签 WordTagsDto dto = new WordTagsDto(); dto.setWord(word); // 获取 tags Set<String> wordTags = wordContext.wordTag().getTag(word); dto.setTags(wordTags); return dto;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordTagsDto.java
WordTagsDto
toString
class WordTagsDto implements Serializable { private String word; private Set<String> tags; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public Set<String> getTags() { return tags; } public void setTags(Set<String> tags) { this.tags = tags; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "WordTagsDto{" + "word='" + word + '\'' + ", tags=" + tags + '}';
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/resultcondition/WordResultConditionEnglishWordMatch.java
WordResultConditionEnglishWordMatch
doMatch
class WordResultConditionEnglishWordMatch extends AbstractWordResultCondition { @Override protected boolean doMatch(IWordResult wordResult, String text, WordValidModeEnum modeEnum, IWordContext context) {<FILL_FUNCTION_BODY>} }
final int startIndex = wordResult.startIndex(); final int endIndex = wordResult.endIndex(); // 判断处理,判断前一个字符是否为英文。如果是,则不满足 if(startIndex > 0) { char preC = text.charAt(startIndex-1); if(CharUtil.isEnglish(preC)) { return false; } } // 判断后一个字符是否为英文 if(endIndex < text.length() - 1) { char afterC = text.charAt(endIndex); if(CharUtil.isEnglish(afterC)) { return false; } } // 判断当前是否为英文单词 for(int i = startIndex; i < endIndex; i++) { char c = text.charAt(i); if(!CharUtil.isEnglish(c)) { return true; } } return true;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/tag/FileWordTag.java
FileWordTag
initWordTagMap
class FileWordTag extends AbstractWordTag { /** * 文件路径 */ protected final String filePath; /** * 词和标签的分隔符 */ protected final String wordSplit; /** * 标签的分隔符 */ protected final String tagSplit; protected Map<String, Set<String>> wordTagMap = new HashMap<>(); public FileWordTag(String filePath) { this(filePath, " ", ","); } public FileWordTag(String filePath, String wordSplit, String tagSplit) { ArgUtil.notEmpty(filePath, "filePath"); ArgUtil.notEmpty(wordSplit, "wordSplit"); ArgUtil.notEmpty(tagSplit, "tagSplit"); this.wordSplit = wordSplit; this.tagSplit = tagSplit; this.filePath = filePath; this.initWordTagMap(); } /** * 初始化 */ protected synchronized void initWordTagMap() {<FILL_FUNCTION_BODY>} protected synchronized void handleInitLine(String line) { String[] strings = line.split(wordSplit); if(strings.length < 2) { return; } String word = strings[0]; String tagText = strings[1]; String[] tags = tagText.split(tagSplit); Set<String> tagSet = new HashSet<>(Arrays.asList(tags)); wordTagMap.put(word, tagSet); } @Override protected Set<String> doGetTag(String word) { return wordTagMap.get(word); } }
List<String> lines = FileUtil.readAllLines(filePath); if(CollectionUtil.isEmpty(lines)) { return; } for(String line : lines) { if(StringUtil.isEmpty(line)) { continue; } // 处理每一行 handleInitLine(line); }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/utils/InnerWordCharUtils.java
InnerWordCharUtils
getMappingChar
class InnerWordCharUtils { private InnerWordCharUtils() { } /** * 英文字母1 * @since 0.0.4 */ private static final String LETTERS_ONE = "ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ" + "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ" + "⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵"; /** * 英文字母2 * @since 0.0.4 */ private static final String LETTERS_TWO = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz"; /** * 英文字母 map * @since 0.0.4 */ private static final Map<Character, Character> LETTER_MAP = Guavas.newHashMap(LETTERS_ONE.length()); static { final int size = LETTERS_ONE.length(); for(int i = 0; i < size; i++) { LETTER_MAP.put(LETTERS_ONE.charAt(i), LETTERS_TWO.charAt(i)); } } /** * 映射后的 char * @param character 待转换的 char * @return 结果 * @since 0.0.4 */ public static Character getMappingChar(final Character character) {<FILL_FUNCTION_BODY>} /** * 构建字符串 * @param chars 字符数组 * @param startIndex 开始位置 * @param endIndex 结束位置 * @return 结果 * @since 0.5.0 */ public static String getString(final char[] chars, final int startIndex, final int endIndex) { // 截取 int len = endIndex - startIndex; return new String(chars, startIndex, len); } /** * 构建字符串 * @param chars 字符数组 * @param wordResult 结果 * @return 结果 * @since 0.5.0 */ public static String getString(final char[] chars, final IWordResult wordResult) { return getString(chars, wordResult.startIndex(), wordResult.endIndex()); } }
final Character mapChar = LETTER_MAP.get(character); if(ObjectUtil.isNotNull(mapChar)) { return mapChar; } return character;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/utils/InnerWordFormatUtils.java
InnerWordFormatUtils
formatCharsMapping
class InnerWordFormatUtils { private InnerWordFormatUtils(){} /** * 空字符数组 * @since 0.6.0 */ private static final char[] EMPTY_CHARS = new char[0]; /** * 格式化 * @param original 原始 * @param context 上下文 * @return 结果 * @since 0.1.1 */ public static String format(final String original, final IWordContext context) { if(StringUtil.isEmpty(original)) { return original; } StringBuilder stringBuilder = new StringBuilder(); IWordFormat charFormat = context.wordFormat(); char[] chars = original.toCharArray(); for(char c : chars) { char cf = charFormat.format(c, context); stringBuilder.append(cf); } return stringBuilder.toString(); } /** * 字符串统一的格式化处理 * @param original 原始文本 * @param context 上下文 * @return 结果 * @since 0.6.0 */ public static Map<Character, Character> formatCharsMapping(final String original, final IWordContext context) {<FILL_FUNCTION_BODY>} /** * 格式化列表 * @param list 列表 * @param context 上下文 * @return 结果 * @since 0。3.0 */ public static List<String> formatWordList(List<String> list, final IWordContext context) { if(CollectionUtil.isEmpty(list)) { return list; } List<String> resultList = new ArrayList<>(list.size()); for(String word : list) { String formatWord = InnerWordFormatUtils.format(word, context); resultList.add(formatWord); } return resultList; } }
if(StringUtil.isEmpty(original)) { return Collections.emptyMap(); } final int len = original.length(); char[] rawChars = original.toCharArray(); Map<Character, Character> map = new HashMap<>(rawChars.length); IWordFormat charFormat = context.wordFormat(); for(int i = 0; i < len; i++) { final char currentChar = rawChars[i]; char formatChar = charFormat.format(currentChar, context); map.put(currentChar, formatChar); } return map;
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/utils/InnerWordNumUtils.java
InnerWordNumUtils
getMappingString
class InnerWordNumUtils { private InnerWordNumUtils(){} private static final String NUM_ONE = "⓪0零º₀⓿○" + "123456789" + "一二三四五六七八九" + "壹贰叁肆伍陆柒捌玖" + "¹²³⁴⁵⁶⁷⁸⁹" + "₁₂₃₄₅₆₇₈₉" + "①②③④⑤⑥⑦⑧⑨" + "⑴⑵⑶⑷⑸⑹⑺⑻⑼" + "⒈⒉⒊⒋⒌⒍⒎⒏⒐" + "❶❷❸❹❺❻❼❽❾" + "➀➁➂➃➄➅➆➇➈" + "➊➋➌➍➎➏➐➑➒" + "㈠㈡㈢㈣㈤㈥㈦㈧㈨" + "⓵⓶⓷⓸⓹⓺⓻⓼⓽" + "㊀㊁㊂㊃㊄㊅㊆㊇㊈" + "ⅰⅱⅲⅳⅴⅵⅶⅷⅸ" + "ⅠⅡⅢⅣⅤⅥⅦⅧⅨ"; private static final String NUM_TWO = "0000000"+ "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789" + "123456789"; /** * 英文字母 map * @since 0.0.4 */ private static final Map<Character, Character> NUMBER_MAP = Guavas.newHashMap(NUM_ONE.length()); static { final int size = NUM_ONE.length(); for(int i = 0; i < size; i++) { NUMBER_MAP.put(NUM_ONE.charAt(i), NUM_TWO.charAt(i)); } } /** * 映射后的 char * @param character 待转换的 char * @return 结果 * @since 0.0.4 */ public static Character getMappingChar(final Character character) { final Character mapChar = NUMBER_MAP.get(character); if(ObjectUtil.isNotNull(mapChar)) { return mapChar; } return character; } public static String getMappingString(final String string) {<FILL_FUNCTION_BODY>} /** * 检查敏感词数量 * <p> * (1)如果未命中敏感词,直接返回 0 * (2)命中敏感词,则返回敏感词的长度。 * * ps: 这里结果进行优化, * 1. 是否包含敏感词。 * 2. 敏感词的长度 * 3. 正常走过字段的长度(便于后期替换优化,避免不必要的循环重复) * * @param txt 文本信息 * @param beginIndex 开始下标 * @param wordValidModeEnum 验证模式 * @param context 执行上下文 * @return 敏感数字对应的长度 * @since 0.0.5 */ private int getSensitiveNumber(final String txt, final int beginIndex, final WordValidModeEnum wordValidModeEnum, final IWordContext context) { return 0; } }
if(StringUtil.isEmpty(string)) { return string; } char[] chars = string.toCharArray(); StringBuilder stringBuilder = new StringBuilder(chars.length); for(char c : chars) { char mapChar = getMappingChar(c); //TODO: stop word 的处理 stringBuilder.append(mapChar); } return stringBuilder.toString();
google_truth
truth/core/src/main/java/com/google/common/truth/AbstractArraySubject.java
AbstractArraySubject
isEmpty
class AbstractArraySubject extends Subject { private final @Nullable Object actual; AbstractArraySubject( FailureMetadata metadata, @Nullable Object actual, @Nullable String typeDescription) { super(metadata, actual, typeDescription); this.actual = actual; } /** Fails if the array is not empty (i.e. {@code array.length > 0}). */ public final void isEmpty() {<FILL_FUNCTION_BODY>} /** Fails if the array is empty (i.e. {@code array.length == 0}). */ public final void isNotEmpty() { if (length() == 0) { failWithoutActual(simpleFact("expected not to be empty")); } } /** * Fails if the array does not have the given length. * * @throws IllegalArgumentException if {@code length < 0} */ public final void hasLength(int length) { checkArgument(length >= 0, "length (%s) must be >= 0", length); check("length").that(length()).isEqualTo(length); } private int length() { return Array.getLength(checkNotNull(actual)); } }
if (length() > 0) { failWithActual(simpleFact("expected to be empty")); }
google_truth
truth/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
BigDecimalSubject
compareValues
class BigDecimalSubject extends ComparableSubject<BigDecimal> { private final @Nullable BigDecimal actual; BigDecimalSubject(FailureMetadata metadata, @Nullable BigDecimal actual) { super(metadata, actual); this.actual = actual; } /** * Fails if the subject's value is not equal to the value of the given {@link BigDecimal}. (i.e., * fails if {@code actual.comparesTo(expected) != 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(BigDecimal expected) { compareValues(expected); } /** * Fails if the subject's value is not equal to the value of the {@link BigDecimal} created from * the expected string (i.e., fails if {@code actual.comparesTo(new BigDecimal(expected)) != 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(String expected) { compareValues(new BigDecimal(expected)); } /** * Fails if the subject's value is not equal to the value of the {@link BigDecimal} created from * the expected {@code long} (i.e., fails if {@code actual.comparesTo(new BigDecimal(expected)) != * 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(long expected) { compareValues(new BigDecimal(expected)); } /** * Fails if the subject's value and scale is not equal to the given {@link BigDecimal}. * * <p><b>Note:</b> If you only want to compare the values of the BigDecimals and not their scales, * use {@link #isEqualToIgnoringScale(BigDecimal)} instead. */ @Override // To express more specific javadoc public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); } /** * Fails if the subject is not equivalent to the given value according to {@link * Comparable#compareTo}, (i.e., fails if {@code a.comparesTo(b) != 0}). This method behaves * identically to (the more clearly named) {@link #isEqualToIgnoringScale(BigDecimal)}. * * <p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link * #isEqualTo(Object)}. */ @Override public void isEquivalentAccordingToCompareTo(@Nullable BigDecimal expected) { compareValues(expected); } private void compareValues(@Nullable BigDecimal expected) {<FILL_FUNCTION_BODY>} }
if (checkNotNull(actual).compareTo(checkNotNull(expected)) != 0) { failWithoutActual(fact("expected", expected), butWas(), simpleFact("(scale is ignored)")); }
google_truth
truth/core/src/main/java/com/google/common/truth/BooleanSubject.java
BooleanSubject
isTrue
class BooleanSubject extends Subject { private final @Nullable Boolean actual; BooleanSubject(FailureMetadata metadata, @Nullable Boolean actual) { super(metadata, actual); this.actual = actual; } /** Fails if the subject is false or {@code null}. */ public void isTrue() {<FILL_FUNCTION_BODY>} /** Fails if the subject is true or {@code null}. */ public void isFalse() { if (actual == null) { isEqualTo(false); // fails } else if (actual) { failWithoutActual(simpleFact("expected to be false")); } } }
if (actual == null) { isEqualTo(true); // fails } else if (!actual) { failWithoutActual(simpleFact("expected to be true")); }
google_truth
truth/core/src/main/java/com/google/common/truth/ClassSubject.java
ClassSubject
isAssignableTo
class ClassSubject extends Subject { private final @Nullable Class<?> actual; ClassSubject(FailureMetadata metadata, @Nullable Class<?> o) { super(metadata, o); this.actual = o; } /** * Fails if this class or interface is not the same as or a subclass or subinterface of, the given * class or interface. */ public void isAssignableTo(Class<?> clazz) {<FILL_FUNCTION_BODY>} }
if (!clazz.isAssignableFrom(checkNotNull(actual))) { failWithActual("expected to be assignable to", clazz.getName()); }
google_truth
truth/core/src/main/java/com/google/common/truth/ComparableSubject.java
ComparableSubject
isLessThan
class ComparableSubject<T extends Comparable<?>> extends Subject { /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call * {@link Subject#check(String, Object...) check(...)}{@code .that(actual)}. */ private final @Nullable T actual; protected ComparableSubject(FailureMetadata metadata, @Nullable T actual) { super(metadata, actual); this.actual = actual; } /** Checks that the subject is in {@code range}. */ public final void isIn(Range<T> range) { if (!range.contains(checkNotNull(actual))) { failWithActual("expected to be in range", range); } } /** Checks that the subject is <i>not</i> in {@code range}. */ public final void isNotIn(Range<T> range) { if (range.contains(checkNotNull(actual))) { failWithActual("expected not to be in range", range); } } /** * Checks that the subject is equivalent to {@code other} according to {@link * Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}). * * <p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link * #isEqualTo(Object)}. */ @SuppressWarnings("unchecked") public void isEquivalentAccordingToCompareTo(@Nullable T expected) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(expected)) != 0) { failWithActual("expected value that sorts equal to", expected); } } /** * Checks that the subject is greater than {@code other}. * * <p>To check that the subject is greater than <i>or equal to</i> {@code other}, use {@link * #isAtLeast}. */ @SuppressWarnings("unchecked") public final void isGreaterThan(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) <= 0) { failWithActual("expected to be greater than", other); } } /** * Checks that the subject is less than {@code other}. * * <p>To check that the subject is less than <i>or equal to</i> {@code other}, use {@link * #isAtMost}. */ @SuppressWarnings("unchecked") public final void isLessThan(@Nullable T other) {<FILL_FUNCTION_BODY>} /** * Checks that the subject is less than or equal to {@code other}. * * <p>To check that the subject is <i>strictly</i> less than {@code other}, use {@link * #isLessThan}. */ @SuppressWarnings("unchecked") public final void isAtMost(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) > 0) { failWithActual("expected to be at most", other); } } /** * Checks that the subject is greater than or equal to {@code other}. * * <p>To check that the subject is <i>strictly</i> greater than {@code other}, use {@link * #isGreaterThan}. */ @SuppressWarnings("unchecked") public final void isAtLeast(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) < 0) { failWithActual("expected to be at least", other); } } }
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) >= 0) { failWithActual("expected to be less than", other); }
google_truth
truth/core/src/main/java/com/google/common/truth/ComparisonFailures.java
ComparisonFailures
removeCommonPrefixAndSuffix
class ComparisonFailures { static ImmutableList<Fact> makeComparisonFailureFacts( ImmutableList<Fact> headFacts, ImmutableList<Fact> tailFacts, String expected, String actual) { return concat(headFacts, formatExpectedAndActual(expected, actual), tailFacts); } /** * Returns one or more facts describing the difference between the given expected and actual * values. * * <p>Currently, that means either 2 facts (one each for expected and actual) or 1 fact with a * diff-like (but much simpler) view. * * <p>In the case of 2 facts, the facts contain either the full expected and actual values or, if * the values have a long prefix or suffix in common, abbreviated values with "…" at the beginning * or end. */ @VisibleForTesting static ImmutableList<Fact> formatExpectedAndActual(String expected, String actual) { ImmutableList<Fact> result; // TODO(cpovirk): Call attention to differences in trailing whitespace. // TODO(cpovirk): And changes in the *kind* of whitespace characters in the middle of the line. result = Platform.makeDiff(expected, actual); if (result != null) { return result; } result = removeCommonPrefixAndSuffix(expected, actual); if (result != null) { return result; } return ImmutableList.of(fact("expected", expected), fact("but was", actual)); } private static @Nullable ImmutableList<Fact> removeCommonPrefixAndSuffix( String expected, String actual) {<FILL_FUNCTION_BODY>} private static final int CONTEXT = 20; private static final int WORTH_HIDING = 60; // From c.g.c.base.Strings. private static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && isHighSurrogate(string.charAt(index)) && isLowSurrogate(string.charAt(index + 1)); } private ComparisonFailures() {} }
int originalExpectedLength = expected.length(); // TODO(cpovirk): Use something like BreakIterator where available. /* * TODO(cpovirk): If the abbreviated values contain newlines, maybe expand them to contain a * newline on each end so that we don't start mid-line? That way, horizontally aligned text will * remain horizontally aligned. But of course, for many multi-line strings, we won't enter this * method at all because we'll generate diff-style output instead. So we might not need to worry * too much about newlines here. */ // TODO(cpovirk): Avoid splitting in the middle of "\r\n." int prefix = commonPrefix(expected, actual).length(); prefix = max(0, prefix - CONTEXT); while (prefix > 0 && validSurrogatePairAt(expected, prefix - 1)) { prefix--; } // No need to hide the prefix unless it's long. if (prefix > 3) { expected = "…" + expected.substring(prefix); actual = "…" + actual.substring(prefix); } int suffix = commonSuffix(expected, actual).length(); suffix = max(0, suffix - CONTEXT); while (suffix > 0 && validSurrogatePairAt(expected, expected.length() - suffix - 1)) { suffix--; } // No need to hide the suffix unless it's long. if (suffix > 3) { expected = expected.substring(0, expected.length() - suffix) + "…"; actual = actual.substring(0, actual.length() - suffix) + "…"; } if (originalExpectedLength - expected.length() < WORTH_HIDING) { return null; } return ImmutableList.of(fact("expected", expected), fact("but was", actual));
google_truth
truth/core/src/main/java/com/google/common/truth/Correspondence.java
ExceptionStore
truncateStackTrace
class ExceptionStore { private final String argumentLabel; private @Nullable StoredException firstCompareException = null; private @Nullable StoredException firstPairingException = null; private @Nullable StoredException firstFormatDiffException = null; static ExceptionStore forIterable() { return new ExceptionStore("elements"); } static ExceptionStore forMapValues() { return new ExceptionStore("values"); } private ExceptionStore(String argumentLabel) { this.argumentLabel = argumentLabel; } /** * Adds an exception that was thrown during a {@code compare} call. * * @param callingClass The class from which the {@code compare} method was called. When * reporting failures, stack traces will be truncated above elements in this class. * @param exception The exception encountered * @param actual The {@code actual} argument to the {@code compare} call during which the * exception was encountered * @param expected The {@code expected} argument to the {@code compare} call during which the * exception was encountered */ void addCompareException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected) { if (firstCompareException == null) { truncateStackTrace(exception, callingClass); firstCompareException = new StoredException(exception, "compare", asList(actual, expected)); } } /** * Adds an exception that was thrown during an {@code apply} call on the function used to key * actual elements. * * @param callingClass The class from which the {@code apply} method was called. When reporting * failures, stack traces will be truncated above elements in this class. * @param exception The exception encountered * @param actual The {@code actual} argument to the {@code apply} call during which the * exception was encountered */ void addActualKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object actual) { if (firstPairingException == null) { truncateStackTrace(exception, callingClass); firstPairingException = new StoredException(exception, "actualKeyFunction.apply", asList(actual)); } } /** * Adds an exception that was thrown during an {@code apply} call on the function used to key * expected elements. * * @param callingClass The class from which the {@code apply} method was called. When reporting * failures, stack traces will be truncated above elements in this class. * @param exception The exception encountered * @param expected The {@code expected} argument to the {@code apply} call during which the * exception was encountered */ void addExpectedKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object expected) { if (firstPairingException == null) { truncateStackTrace(exception, callingClass); firstPairingException = new StoredException(exception, "expectedKeyFunction.apply", asList(expected)); } } /** * Adds an exception that was thrown during a {@code formatDiff} call. * * @param callingClass The class from which the {@code formatDiff} method was called. When * reporting failures, stack traces will be truncated above elements in this class. * @param exception The exception encountered * @param actual The {@code actual} argument to the {@code formatDiff} call during which the * exception was encountered * @param expected The {@code expected} argument to the {@code formatDiff} call during which the * exception was encountered */ void addFormatDiffException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected) { if (firstFormatDiffException == null) { truncateStackTrace(exception, callingClass); firstFormatDiffException = new StoredException(exception, "formatDiff", asList(actual, expected)); } } /** Returns whether any exceptions thrown during {@code compare} calls were stored. */ boolean hasCompareException() { return firstCompareException != null; } /** * Returns facts to use in a failure message when the exceptions from {@code compare} calls are * the main cause of the failure. At least one exception thrown during a {@code compare} call * must have been stored, and no exceptions from a {@code formatDiff} call. Assertions should * use this when exceptions were thrown while comparing elements and no more meaningful failure * was discovered by assuming a false return and continuing (see the javadoc for {@link * Correspondence#compare}). C.f. {@link #describeAsAdditionalInfo}. */ ImmutableList<Fact> describeAsMainCause() { checkState(firstCompareException != null); // We won't do pairing or diff formatting unless a more meaningful failure was found, and if a // more meaningful failure was found then we shouldn't be using this method: checkState(firstPairingException == null); checkState(firstFormatDiffException == null); return ImmutableList.of( simpleFact("one or more exceptions were thrown while comparing " + argumentLabel), fact("first exception", firstCompareException.describe())); } /** * If any exceptions are stored, returns facts to use in a failure message when the exceptions * should be noted as additional info; if empty, returns an empty list. Assertions should use * this when exceptions were thrown while comparing elements but more meaningful failures were * discovered by assuming a false return and continuing (see the javadoc for {@link * Correspondence#compare}), or when exceptions were thrown by other methods while generating * the failure message. C.f. {@link #describeAsMainCause}. */ ImmutableList<Fact> describeAsAdditionalInfo() { ImmutableList.Builder<Fact> builder = ImmutableList.builder(); if (firstCompareException != null) { builder.add( simpleFact( "additionally, one or more exceptions were thrown while comparing " + argumentLabel)); builder.add(fact("first exception", firstCompareException.describe())); } if (firstPairingException != null) { builder.add( simpleFact( "additionally, one or more exceptions were thrown while keying " + argumentLabel + " for pairing")); builder.add(fact("first exception", firstPairingException.describe())); } if (firstFormatDiffException != null) { builder.add( simpleFact("additionally, one or more exceptions were thrown while formatting diffs")); builder.add(fact("first exception", firstFormatDiffException.describe())); } return builder.build(); } private static void truncateStackTrace(Exception exception, Class<?> callingClass) {<FILL_FUNCTION_BODY>} }
StackTraceElement[] original = exception.getStackTrace(); int keep = 0; while (keep < original.length && !original[keep].getClassName().equals(callingClass.getName())) { keep++; } exception.setStackTrace(Arrays.copyOf(original, keep));
google_truth
truth/core/src/main/java/com/google/common/truth/DoubleSubject.java
TolerantDoubleComparison
of
class TolerantDoubleComparison { // Prevent subclassing outside of this class private TolerantDoubleComparison() {} /** * Fails if the subject was expected to be within the tolerance of the given value but was not * <i>or</i> if it was expected <i>not</i> to be within the tolerance but was. The subject and * tolerance are specified earlier in the fluent call chain. */ public abstract void of(double expectedDouble); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on TolerantDoubleComparison. If * you meant to compare doubles, use {@link #of(double)} instead. */ @Deprecated @Override public boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to compare doubles, use .of(double) instead."); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on TolerantDoubleComparison */ @Deprecated @Override public int hashCode() { throw new UnsupportedOperationException("Subject.hashCode() is not supported."); } } /** * Prepares for a check that the subject is a finite number within the given tolerance of an * expected value that will be provided in the next call in the fluent chain. * * <p>The check will fail if either the subject or the object is {@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}. To check for those values, use {@link * #isPositiveInfinity}, {@link #isNegativeInfinity}, {@link #isNaN}, or (with more generality) * {@link #isEqualTo}. * * <p>The check will pass if both values are zero, even if one is {@code 0.0} and the other is * {@code -0.0}. Use {@code #isEqualTo} to assert that a value is exactly {@code 0.0} or that it * is exactly {@code -0.0}. * * <p>You can use a tolerance of {@code 0.0} to assert the exact equality of finite doubles, but * often {@link #isEqualTo} is preferable (note the different behaviours around non-finite values * and {@code -0.0}). See the documentation on {@link #isEqualTo} for advice on when exact * equality assertions are appropriate. * * @param tolerance an inclusive upper bound on the difference between the subject and object * allowed by the check, which must be a non-negative finite value, i.e. not {@link * Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0} */ public TolerantDoubleComparison isWithin(double tolerance) { return new TolerantDoubleComparison() { @Override public void of(double expected) { Double actual = DoubleSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected); checkTolerance(tolerance); if (!equalWithinTolerance(actual, expected, tolerance)) { failWithoutActual( fact("expected", doubleToString(expected)), butWas(), fact("outside tolerance", doubleToString(tolerance))); } } }; } /** * Prepares for a check that the subject is a finite number not within the given tolerance of an * expected value that will be provided in the next call in the fluent chain. * * <p>The check will fail if either the subject or the object is {@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}. See {@link #isFinite}, {@link * #isNotNaN}, or {@link #isNotEqualTo} for checks with other behaviours. * * <p>The check will fail if both values are zero, even if one is {@code 0.0} and the other is * {@code -0.0}. Use {@code #isNotEqualTo} for a test which fails for a value of exactly zero with * one sign but passes for zero with the opposite sign. * * <p>You can use a tolerance of {@code 0.0} to assert the exact non-equality of finite doubles, * but sometimes {@link #isNotEqualTo} is preferable (note the different behaviours around * non-finite values and {@code -0.0}). * * @param tolerance an exclusive lower bound on the difference between the subject and object * allowed by the check, which must be a non-negative finite value, i.e. not {@code * Double.NaN}, {@code Double.POSITIVE_INFINITY}, or negative, including {@code -0.0} */ public TolerantDoubleComparison isNotWithin(double tolerance) { return new TolerantDoubleComparison() { @Override public void of(double expected) {<FILL_FUNCTION_BODY>
Double actual = DoubleSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected); checkTolerance(tolerance); if (!notEqualWithinTolerance(actual, expected, tolerance)) { failWithoutActual( fact("expected not to be", doubleToString(expected)), butWas(), fact("within tolerance", doubleToString(tolerance))); }
google_truth
truth/core/src/main/java/com/google/common/truth/Expect.java
ExpectationGatherer
doCheckInRuleContext
class ExpectationGatherer implements FailureStrategy { @GuardedBy("this") private final List<AssertionError> failures = new ArrayList<>(); @GuardedBy("this") private TestPhase inRuleContext = BEFORE; ExpectationGatherer() {} @Override public synchronized void fail(AssertionError failure) { record(failure); } synchronized void enterRuleContext() { checkState(inRuleContext == BEFORE); inRuleContext = DURING; } synchronized void leaveRuleContext(@Nullable Throwable caught) throws Throwable { try { if (caught == null) { doLeaveRuleContext(); } else { doLeaveRuleContext(caught); } /* * We'd like to check this even if an exception was thrown, but we don't want to override * the "real" failure. TODO(cpovirk): Maybe attach as a suppressed exception once we require * a newer version of Android. */ checkState(inRuleContext == DURING); } finally { inRuleContext = AFTER; } } synchronized void checkInRuleContext() { doCheckInRuleContext(null); } synchronized boolean hasFailures() { return !failures.isEmpty(); } @Override public synchronized String toString() { if (failures.isEmpty()) { return "No expectation failed."; } int numFailures = failures.size(); StringBuilder message = new StringBuilder() .append(numFailures) .append(numFailures > 1 ? " expectations" : " expectation") .append(" failed:\n"); int countLength = String.valueOf(failures.size() + 1).length(); int count = 0; for (AssertionError failure : failures) { count++; message.append(" "); message.append(padStart(String.valueOf(count), countLength, ' ')); message.append(". "); if (count == 1) { appendIndented(countLength, message, getStackTraceAsString(failure)); } else { appendIndented( countLength, message, printSubsequentFailure(failures.get(0).getStackTrace(), failure)); } message.append("\n"); } return message.toString(); } // String.repeat is not available under Java 8 and old versions of Android. @SuppressWarnings({"StringsRepeat", "InlineMeInliner"}) private static void appendIndented(int countLength, StringBuilder builder, String toAppend) { int indent = countLength + 4; // " " and ". " builder.append(toAppend.replace("\n", "\n" + repeat(" ", indent))); } private String printSubsequentFailure( StackTraceElement[] baseTraceFrames, AssertionError toPrint) { Exception e = new RuntimeException("__EXCEPTION_MARKER__", toPrint); e.setStackTrace(baseTraceFrames); String s = Throwables.getStackTraceAsString(e); // Force single line reluctant matching return s.replaceFirst("(?s)^.*?__EXCEPTION_MARKER__.*?Caused by:\\s+", ""); } @GuardedBy("this") private void doCheckInRuleContext(@Nullable AssertionError failure) {<FILL_FUNCTION_BODY>} @GuardedBy("this") private void doLeaveRuleContext() { if (hasFailures()) { throw SimpleAssertionError.createWithNoStack(this.toString()); } } @GuardedBy("this") private void doLeaveRuleContext(Throwable caught) throws Throwable { if (hasFailures()) { String message = caught instanceof AssumptionViolatedException ? "Also, after those failures, an assumption was violated:" : "Also, after those failures, an exception was thrown:"; record(SimpleAssertionError.createWithNoStack(message, caught)); throw SimpleAssertionError.createWithNoStack(this.toString()); } else { throw caught; } } @GuardedBy("this") private void record(AssertionError failure) { doCheckInRuleContext(failure); failures.add(failure); } }
switch (inRuleContext) { case BEFORE: throw new IllegalStateException( "assertion made on Expect instance, but it's not enabled as a @Rule.", failure); case DURING: return; case AFTER: throw new IllegalStateException( "assertion made on Expect instance, but its @Rule has already completed. Maybe " + "you're making assertions from a background thread and not waiting for them to " + "complete, or maybe you've shared an Expect instance across multiple tests? " + "We're throwing this exception to warn you that your assertion would have been " + "ignored. However, this exception might not cause any test to fail, or it " + "might cause some subsequent test to fail rather than the test that caused the " + "problem.", failure); } throw new AssertionError();
google_truth
truth/core/src/main/java/com/google/common/truth/ExpectFailure.java
ExpectFailure
captureFailure
class ExpectFailure implements Platform.JUnitTestRule { private boolean inRuleContext = false; private boolean failureExpected = false; private @Nullable AssertionError failure = null; /** * Creates a new instance for use as a {@code @Rule}. See the class documentation for details, and * consider using {@linkplain #expectFailure the lambda version} instead. */ public ExpectFailure() {} /** * Returns a test verb that expects the chained assertion to fail, and makes the failure available * via {@link #getFailure}. * * <p>An instance of {@code ExpectFailure} supports only one {@code whenTesting} call per test * method. The static {@link #expectFailure} method, by contrast, does not have this limitation. */ public StandardSubjectBuilder whenTesting() { checkState(inRuleContext, "ExpectFailure must be used as a JUnit @Rule"); if (failure != null) { throw SimpleAssertionError.create("ExpectFailure already captured a failure", failure); } if (failureExpected) { throw new AssertionError( "ExpectFailure.whenTesting() called previously, but did not capture a failure."); } failureExpected = true; return StandardSubjectBuilder.forCustomFailureStrategy(this::captureFailure); } /** * Enters rule context to be ready to capture failures. * * <p>This should be rarely used directly, except if this class is as a long living object but not * as a JUnit rule, like truth subject tests where for GWT compatible reasons. */ void enterRuleContext() { this.inRuleContext = true; } /** Leaves rule context and verify if a failure has been caught if it's expected. */ void leaveRuleContext() { this.inRuleContext = false; } /** * Ensures a failure is caught if it's expected (i.e., {@link #whenTesting} is called) and throws * error if not. */ void ensureFailureCaught() { if (failureExpected && failure == null) { throw new AssertionError( "ExpectFailure.whenTesting() invoked, but no failure was caught." + Platform.EXPECT_FAILURE_WARNING_IF_GWT); } } /** Returns the captured failure, if one occurred. */ public AssertionError getFailure() { if (failure == null) { throw new AssertionError("ExpectFailure did not capture a failure."); } return failure; } /** * Captures the provided failure, or throws an {@link AssertionError} if a failure had previously * been captured. */ private void captureFailure(AssertionError captured) {<FILL_FUNCTION_BODY>} /** * Static alternative that directly returns the triggered failure. This is intended to be used in * Java 8+ tests similar to {@code expectThrows()}: * * <p>{@code AssertionError failure = expectFailure(whenTesting -> * whenTesting.that(4).isNotEqualTo(4));} */ @CanIgnoreReturnValue public static AssertionError expectFailure(StandardSubjectBuilderCallback assertionCallback) { ExpectFailure expectFailure = new ExpectFailure(); expectFailure.enterRuleContext(); // safe since this instance doesn't leave this method assertionCallback.invokeAssertion(expectFailure.whenTesting()); return expectFailure.getFailure(); } /** * Static alternative that directly returns the triggered failure. This is intended to be used in * Java 8+ tests similar to {@code expectThrows()}: * * <p>{@code AssertionError failure = expectFailureAbout(myTypes(), whenTesting -> * whenTesting.that(myType).hasProperty());} */ @CanIgnoreReturnValue public static <S extends Subject, A> AssertionError expectFailureAbout( Subject.Factory<S, A> factory, SimpleSubjectBuilderCallback<S, A> assertionCallback) { return expectFailure( whenTesting -> assertionCallback.invokeAssertion(whenTesting.about(factory))); } /** * Creates a subject for asserting about the given {@link AssertionError}, usually one produced by * Truth. */ public static TruthFailureSubject assertThat(@Nullable AssertionError actual) { return assertAbout(truthFailures()).that(actual); } @Override @GwtIncompatible("org.junit.rules.TestRule") @J2ktIncompatible public Statement apply(Statement base, Description description) { checkNotNull(base); checkNotNull(description); return new Statement() { @Override public void evaluate() throws Throwable { enterRuleContext(); try { base.evaluate(); } finally { leaveRuleContext(); } ensureFailureCaught(); } }; } /** * A "functional interface" for {@link #expectFailure expectFailure()} to invoke and capture * failures. * * <p>Java 8+ users should pass a lambda to {@code .expectFailure()} rather than directly * implement this interface. Java 7+ users can define an {@code @Rule ExpectFailure} instance * instead, however if you prefer the {@code .expectFailure()} pattern you can use this interface * to pass in an anonymous class. */ public interface StandardSubjectBuilderCallback { void invokeAssertion(StandardSubjectBuilder whenTesting); } /** * A "functional interface" for {@link #expectFailureAbout expectFailureAbout()} to invoke and * capture failures. * * <p>Java 8+ users should pass a lambda to {@code .expectFailureAbout()} rather than directly * implement this interface. Java 7+ users can define an {@code @Rule ExpectFailure} instance * instead, however if you prefer the {@code .expectFailureAbout()} pattern you can use this * interface to pass in an anonymous class. */ public interface SimpleSubjectBuilderCallback<S extends Subject, A> { void invokeAssertion(SimpleSubjectBuilder<S, A> whenTesting); } }
if (failure != null) { // TODO(diamondm) is it worthwhile to add the failures as suppressed exceptions? throw new AssertionError( lenientFormat( "ExpectFailure.whenTesting() caught multiple failures:\n\n%s\n\n%s\n", Platform.getStackTraceAsString(failure), Platform.getStackTraceAsString(captured))); } failure = captured;
google_truth
truth/core/src/main/java/com/google/common/truth/Fact.java
Fact
toString
class Fact implements Serializable { /** * Creates a fact with the given key and value, which will be printed in a format like "key: * value." The value is converted to a string by calling {@code String.valueOf} on it. */ public static Fact fact(String key, @Nullable Object value) { return new Fact(key, String.valueOf(value)); } /** * Creates a fact with no value, which will be printed in the format "key" (with no colon or * value). * * <p>In most cases, prefer {@linkplain #fact key-value facts}, which give Truth more flexibility * in how to format the fact for display. {@code simpleFact} is useful primarily for: * * <ul> * <li>messages from no-arg assertions. For example, {@code isNotEmpty()} would generate the * fact "expected not to be empty" * <li>prose that is part of a larger message. For example, {@code contains()} sometimes * displays facts like "expected to contain: ..." <i>"but did not"</i> "though it did * contain: ..." * </ul> */ public static Fact simpleFact(String key) { return new Fact(key, null); } final String key; final @Nullable String value; private Fact(String key, @Nullable String value) { this.key = checkNotNull(key); this.value = value; } /** * Returns a simple string representation for the fact. While this is used in the output of {@code * TruthFailureSubject}, it's not used in normal failure messages, which automatically align facts * horizontally and indent multiline values. */ @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Formats the given messages and facts into a string for use as the message of a test failure. In * particular, this method horizontally aligns the beginning of fact values. */ static String makeMessage(ImmutableList<String> messages, ImmutableList<Fact> facts) { int longestKeyLength = 0; boolean seenNewlineInValue = false; for (Fact fact : facts) { if (fact.value != null) { longestKeyLength = max(longestKeyLength, fact.key.length()); // TODO(cpovirk): Look for other kinds of newlines. seenNewlineInValue |= fact.value.contains("\n"); } } StringBuilder builder = new StringBuilder(); for (String message : messages) { builder.append(message); builder.append('\n'); } /* * *Usually* the first fact is printed at the beginning of a new line. However, when this * exception is the cause of another exception, that exception will print it starting after * "Caused by: " on the same line. The other exception sometimes also reuses this message as its * own message. In both of those scenarios, the first line doesn't start at column 0, so the * horizontal alignment is thrown off. * * There's not much we can do about this, short of always starting with a newline (which would * leave a blank line at the beginning of the message in the normal case). */ for (Fact fact : facts) { if (fact.value == null) { builder.append(fact.key); } else if (seenNewlineInValue) { builder.append(fact.key); builder.append(":\n"); builder.append(indent(fact.value)); } else { builder.append(padEnd(fact.key, longestKeyLength, ' ')); builder.append(": "); builder.append(fact.value); } builder.append('\n'); } if (builder.length() > 0) { builder.setLength(builder.length() - 1); // remove trailing \n } return builder.toString(); } private static String indent(String value) { // We don't want to indent with \t because the text would align exactly with the stack trace. // We don't want to indent with \t\t because it would be very far for people with 8-space tabs. // Let's compromise and indent by 4 spaces, which is different than both 2- and 8-space tabs. return " " + value.replace("\n", "\n "); } }
return value == null ? key : key + ": " + value;
google_truth
truth/core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
GuavaOptionalSubject
hasValue
class GuavaOptionalSubject extends Subject { @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type private final @Nullable Optional<?> actual; GuavaOptionalSubject( FailureMetadata metadata, @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type @Nullable Optional<?> actual, @Nullable String typeDescription) { super(metadata, actual, typeDescription); this.actual = actual; } /** Fails if the {@link Optional}{@code <T>} is absent or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link Optional}{@code <T>} is present or the subject is null. */ public void isAbsent() { if (actual == null) { failWithActual(simpleFact("expected absent optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be absent"), fact("but was present with value", actual.get())); } } /** * Fails if the {@link Optional}{@code <T>} does not have the given value or the subject is null. * * <p>To make more complex assertions on the optional's value split your assertion in two: * * <pre>{@code * assertThat(myOptional).isPresent(); * assertThat(myOptional.get()).contains("foo"); * }</pre> */ public void hasValue(@Nullable Object expected) {<FILL_FUNCTION_BODY>} }
if (expected == null) { throw new NullPointerException("Optional cannot have a null value."); } if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected); }
google_truth
truth/core/src/main/java/com/google/common/truth/IntegerSubject.java
TolerantIntegerComparison
of
class TolerantIntegerComparison { // Prevent subclassing outside of this class private TolerantIntegerComparison() {} /** * Fails if the subject was expected to be within the tolerance of the given value but was not * <i>or</i> if it was expected <i>not</i> to be within the tolerance but was. The subject and * tolerance are specified earlier in the fluent call chain. */ public abstract void of(int expectedInteger); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on TolerantIntegerComparison. If * you meant to compare ints, use {@link #of(int)} instead. */ @Deprecated @Override public boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to compare ints, use .of(int) instead."); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on TolerantIntegerComparison */ @Deprecated @Override public int hashCode() { throw new UnsupportedOperationException("Subject.hashCode() is not supported."); } } /** * Prepares for a check that the subject is a number within the given tolerance of an expected * value that will be provided in the next call in the fluent chain. * * @param tolerance an inclusive upper bound on the difference between the subject and object * allowed by the check, which must be a non-negative value. * @since 1.2 */ public TolerantIntegerComparison isWithin(int tolerance) { return new TolerantIntegerComparison() { @Override public void of(int expected) {<FILL_FUNCTION_BODY>
Integer actual = IntegerSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected); checkTolerance(tolerance); if (!equalWithinTolerance(actual, expected, tolerance)) { failWithoutActual( fact("expected", Integer.toString(expected)), butWas(), fact("outside tolerance", Integer.toString(tolerance))); }
google_truth
truth/core/src/main/java/com/google/common/truth/IterableSubject.java
Pairer
pair
class Pairer { private final Function<? super A, ?> actualKeyFunction; private final Function<? super E, ?> expectedKeyFunction; Pairer(Function<? super A, ?> actualKeyFunction, Function<? super E, ?> expectedKeyFunction) { this.actualKeyFunction = actualKeyFunction; this.expectedKeyFunction = expectedKeyFunction; } /** * Returns a {@link Pairing} of the given expected and actual values, or {@code null} if the * expected values are not uniquely keyed. */ @Nullable Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions) {<FILL_FUNCTION_BODY>} List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions) { Object key = expectedKey(expectedValue, exceptions); List<A> matches = new ArrayList<>(); if (key != null) { for (A actual : actualValues) { if (key.equals(actualKey(actual, exceptions))) { matches.add(actual); } } } return matches; } private @Nullable Object actualKey(A actual, Correspondence.ExceptionStore exceptions) { try { return actualKeyFunction.apply(actual); } catch (RuntimeException e) { exceptions.addActualKeyFunctionException( IterableSubject.UsingCorrespondence.Pairer.class, e, actual); return null; } } private @Nullable Object expectedKey(E expected, Correspondence.ExceptionStore exceptions) { try { return expectedKeyFunction.apply(expected); } catch (RuntimeException e) { exceptions.addExpectedKeyFunctionException( IterableSubject.UsingCorrespondence.Pairer.class, e, expected); return null; } } }
Pairing pairing = new Pairing(); // Populate expectedKeys with the keys of the corresponding elements of expectedValues. // We do this ahead of time to avoid invoking the key function twice for each element. List<@Nullable Object> expectedKeys = new ArrayList<>(expectedValues.size()); for (E expected : expectedValues) { expectedKeys.add(expectedKey(expected, exceptions)); } // Populate pairedKeysToExpectedValues with *all* the expected values with non-null keys. // We will remove the unpaired keys later. Return null if we find a duplicate key. for (int i = 0; i < expectedValues.size(); i++) { E expected = expectedValues.get(i); Object key = expectedKeys.get(i); if (key != null) { if (pairing.pairedKeysToExpectedValues.containsKey(key)) { return null; } else { pairing.pairedKeysToExpectedValues.put(key, expected); } } } // Populate pairedKeysToActualValues and unpairedActualValues. for (A actual : actualValues) { Object key = actualKey(actual, exceptions); if (pairing.pairedKeysToExpectedValues.containsKey(key)) { pairing.pairedKeysToActualValues.put(checkNotNull(key), actual); } else { pairing.unpairedActualValues.add(actual); } } // Populate unpairedExpectedValues and remove unpaired keys from pairedKeysToExpectedValues. for (int i = 0; i < expectedValues.size(); i++) { E expected = expectedValues.get(i); Object key = expectedKeys.get(i); if (!pairing.pairedKeysToActualValues.containsKey(key)) { pairing.unpairedExpectedValues.add(expected); pairing.pairedKeysToExpectedValues.remove(key); } } return pairing;
google_truth
truth/core/src/main/java/com/google/common/truth/LazyMessage.java
LazyMessage
evaluateAll
class LazyMessage { private final String format; private final @Nullable Object[] args; LazyMessage(String format, @Nullable Object... args) { this.format = format; this.args = args; int placeholders = countPlaceholders(format); checkArgument( placeholders == args.length, "Incorrect number of args (%s) for the given placeholders (%s) in string template:\"%s\"", args.length, placeholders, format); } @Override public String toString() { return lenientFormat(format, args); } @VisibleForTesting static int countPlaceholders(String template) { int index = 0; int count = 0; while (true) { index = template.indexOf("%s", index); if (index == -1) { break; } index++; count++; } return count; } static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages) {<FILL_FUNCTION_BODY>} }
ImmutableList.Builder<String> result = ImmutableList.builder(); for (LazyMessage message : messages) { result.add(message.toString()); } return result.build();
google_truth
truth/core/src/main/java/com/google/common/truth/LongSubject.java
TolerantLongComparison
isNotWithin
class TolerantLongComparison { // Prevent subclassing outside of this class private TolerantLongComparison() {} /** * Fails if the subject was expected to be within the tolerance of the given value but was not * <i>or</i> if it was expected <i>not</i> to be within the tolerance but was. The subject and * tolerance are specified earlier in the fluent call chain. */ public abstract void of(long expectedLong); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on TolerantLongComparison. If you * meant to compare longs, use {@link #of(long)} instead. */ @Deprecated @Override public boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to compare longs, use .of(long) instead."); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on TolerantLongComparison */ @Deprecated @Override public int hashCode() { throw new UnsupportedOperationException("Subject.hashCode() is not supported."); } } /** * Prepares for a check that the subject is a number within the given tolerance of an expected * value that will be provided in the next call in the fluent chain. * * @param tolerance an inclusive upper bound on the difference between the subject and object * allowed by the check, which must be a non-negative value. * @since 1.2 */ public TolerantLongComparison isWithin(long tolerance) { return new TolerantLongComparison() { @Override public void of(long expected) { Long actual = LongSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected); checkTolerance(tolerance); if (!equalWithinTolerance(actual, expected, tolerance)) { failWithoutActual( fact("expected", Long.toString(expected)), butWas(), fact("outside tolerance", Long.toString(tolerance))); } } }; } /** * Prepares for a check that the subject is a number not within the given tolerance of an expected * value that will be provided in the next call in the fluent chain. * * @param tolerance an exclusive lower bound on the difference between the subject and object * allowed by the check, which must be a non-negative value. * @since 1.2 */ public TolerantLongComparison isNotWithin(long tolerance) {<FILL_FUNCTION_BODY>
return new TolerantLongComparison() { @Override public void of(long expected) { Long actual = LongSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected); checkTolerance(tolerance); if (equalWithinTolerance(actual, expected, tolerance)) { failWithoutActual( fact("expected not to be", Long.toString(expected)), butWas(), fact("within tolerance", Long.toString(tolerance))); } } };
google_truth
truth/core/src/main/java/com/google/common/truth/MathUtil.java
MathUtil
equalWithinTolerance
class MathUtil { private MathUtil() {} /** * Returns true iff {@code left} and {@code right} are values within {@code tolerance} of each * other. */ /* package */ static boolean equalWithinTolerance(long left, long right, long tolerance) {<FILL_FUNCTION_BODY>} /** * Returns true iff {@code left} and {@code right} are values within {@code tolerance} of each * other. */ /* package */ static boolean equalWithinTolerance(int left, int right, int tolerance) { try { // subtractExact is always desugared. @SuppressWarnings("Java7ApiChecker") int absDiff = Math.abs(subtractExact(left, right)); return 0 <= absDiff && absDiff <= Math.abs(tolerance); } catch (ArithmeticException e) { // The numbers are so far apart their difference isn't even a int. return false; } } /** * Returns true iff {@code left} and {@code right} are finite values within {@code tolerance} of * each other. Note that both this method and {@link #notEqualWithinTolerance} returns false if * either {@code left} or {@code right} is infinite or NaN. */ public static boolean equalWithinTolerance(double left, double right, double tolerance) { return Math.abs(left - right) <= Math.abs(tolerance); } /** * Returns true iff {@code left} and {@code right} are finite values within {@code tolerance} of * each other. Note that both this method and {@link #notEqualWithinTolerance} returns false if * either {@code left} or {@code right} is infinite or NaN. */ public static boolean equalWithinTolerance(float left, float right, float tolerance) { return equalWithinTolerance((double) left, (double) right, (double) tolerance); } /** * Returns true iff {@code left} and {@code right} are finite values not within {@code tolerance} * of each other. Note that both this method and {@link #equalWithinTolerance} returns false if * either {@code left} or {@code right} is infinite or NaN. */ public static boolean notEqualWithinTolerance(double left, double right, double tolerance) { if (Doubles.isFinite(left) && Doubles.isFinite(right)) { return Math.abs(left - right) > Math.abs(tolerance); } else { return false; } } /** * Returns true iff {@code left} and {@code right} are finite values not within {@code tolerance} * of each other. Note that both this method and {@link #equalWithinTolerance} returns false if * either {@code left} or {@code right} is infinite or NaN. */ public static boolean notEqualWithinTolerance(float left, float right, float tolerance) { return notEqualWithinTolerance((double) left, (double) right, (double) tolerance); } }
try { // subtractExact is always desugared. @SuppressWarnings("Java7ApiChecker") long absDiff = Math.abs(subtractExact(left, right)); return 0 <= absDiff && absDiff <= Math.abs(tolerance); } catch (ArithmeticException e) { // The numbers are so far apart their difference isn't even a long. return false; }
google_truth
truth/core/src/main/java/com/google/common/truth/MultisetSubject.java
MultisetSubject
hasCount
class MultisetSubject extends IterableSubject { private final @Nullable Multiset<?> actual; MultisetSubject(FailureMetadata metadata, @Nullable Multiset<?> multiset) { super(metadata, multiset, /* typeDescriptionOverride= */ "multiset"); this.actual = multiset; } /** Fails if the element does not have the given count. */ public final void hasCount(@Nullable Object element, int expectedCount) {<FILL_FUNCTION_BODY>} }
checkArgument(expectedCount >= 0, "expectedCount(%s) must be >= 0", expectedCount); int actualCount = checkNotNull(actual).count(element); check("count(%s)", element).that(actualCount).isEqualTo(expectedCount);
google_truth
truth/core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
OptionalDoubleSubject
isEmpty
class OptionalDoubleSubject extends Subject { private final OptionalDouble actual; OptionalDoubleSubject( FailureMetadata failureMetadata, @Nullable OptionalDouble subject, @Nullable String typeDescription) { super(failureMetadata, subject, typeDescription); this.actual = subject; } /** Fails if the {@link OptionalDouble} is empty or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link OptionalDouble} is present or the subject is null. */ public void isEmpty() {<FILL_FUNCTION_BODY>} /** * Fails if the {@link OptionalDouble} does not have the given value or the subject is null. This * method is <i>not</i> recommended when the code under test is doing any kind of arithmetic, * since the exact result of floating point arithmetic is sensitive to apparently trivial changes. * More sophisticated comparisons can be done using {@code assertThat(optional.getAsDouble())…}. * This method is recommended when the code under test is specified as either copying a value * without modification from its input or returning a well-defined literal or constant value. */ public void hasValue(double expected) { if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("getAsDouble()") .that(actual.getAsDouble()) .isEqualTo(expected); } } /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(optionalDoubles()).that(optional)....}. Now, you can perform * assertions like that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionalDoubles()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionalDoubles()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalDoubleSubject, OptionalDouble> optionalDoubles() { return (metadata, subject) -> new OptionalDoubleSubject(metadata, subject, "optionalDouble"); } }
if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsDouble())); }
google_truth
truth/core/src/main/java/com/google/common/truth/OptionalIntSubject.java
OptionalIntSubject
hasValue
class OptionalIntSubject extends Subject { private final OptionalInt actual; OptionalIntSubject( FailureMetadata failureMetadata, @Nullable OptionalInt subject, @Nullable String typeDescription) { super(failureMetadata, subject, typeDescription); this.actual = subject; } /** Fails if the {@link OptionalInt} is empty or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link OptionalInt} is present or the subject is null. */ public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsInt())); } } /** * Fails if the {@link OptionalInt} does not have the given value or the subject is null. More * sophisticated comparisons can be done using {@code assertThat(optional.getAsInt())…}. */ public void hasValue(int expected) {<FILL_FUNCTION_BODY>} /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(optionalInts()).that(optional)....}. Now, you can perform * assertions like that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionalInts()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionalInts()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalIntSubject, OptionalInt> optionalInts() { return (metadata, subject) -> new OptionalIntSubject(metadata, subject, "optionalInt"); } }
if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("getAsInt()").that(actual.getAsInt()).isEqualTo(expected); }
google_truth
truth/core/src/main/java/com/google/common/truth/OptionalLongSubject.java
OptionalLongSubject
isEmpty
class OptionalLongSubject extends Subject { private final OptionalLong actual; OptionalLongSubject( FailureMetadata failureMetadata, @Nullable OptionalLong subject, @Nullable String typeDescription) { super(failureMetadata, subject, typeDescription); this.actual = subject; } /** Fails if the {@link OptionalLong} is empty or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link OptionalLong} is present or the subject is null. */ public void isEmpty() {<FILL_FUNCTION_BODY>} /** * Fails if the {@link OptionalLong} does not have the given value or the subject is null. More * sophisticated comparisons can be done using {@code assertThat(optional.getAsLong())…}. */ public void hasValue(long expected) { if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("getAsLong()").that(actual.getAsLong()).isEqualTo(expected); } } /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(optionalLongs()).that(optional)....}. Now, you can perform * assertions like that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionalLongs()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionalLongs()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalLongSubject, OptionalLong> optionalLongs() { return (metadata, subject) -> new OptionalLongSubject(metadata, subject, "optionalLong"); } }
if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsLong())); }
google_truth
truth/core/src/main/java/com/google/common/truth/OptionalSubject.java
OptionalSubject
hasValue
class OptionalSubject extends Subject { @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type private final @Nullable Optional<?> actual; OptionalSubject( FailureMetadata failureMetadata, @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type @Nullable Optional<?> subject, @Nullable String typeDescription) { super(failureMetadata, subject, typeDescription); this.actual = subject; } // TODO(cpovirk): Consider making OptionalIntSubject and OptionalLongSubject delegate to this. /** Fails if the {@link Optional}{@code <T>} is empty or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link Optional}{@code <T>} is present or the subject is null. */ public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.get())); } } /** * Fails if the {@link Optional}{@code <T>} does not have the given value or the subject is null. * * <p>To make more complex assertions on the optional's value split your assertion in two: * * <pre>{@code * assertThat(myOptional).isPresent(); * assertThat(myOptional.get()).contains("foo"); * }</pre> */ public void hasValue(@Nullable Object expected) {<FILL_FUNCTION_BODY>} /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like * that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionals()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionals()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalSubject, Optional<?>> optionals() { return (metadata, subject) -> new OptionalSubject(metadata, subject, "optional"); } }
if (expected == null) { throw new NullPointerException("Optional cannot have a null value."); } if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was empty")); } else { checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected); }
google_truth
truth/core/src/main/java/com/google/common/truth/SubjectUtils.java
DuplicateGroupedAndTyped
retainMatchingToString
class DuplicateGroupedAndTyped { final NonHashingMultiset<?> valuesAndMaybeTypes; final Optional<String> homogeneousTypeToDisplay; DuplicateGroupedAndTyped( NonHashingMultiset<?> valuesAndMaybeTypes, Optional<String> homogeneousTypeToDisplay) { this.valuesAndMaybeTypes = valuesAndMaybeTypes; this.homogeneousTypeToDisplay = homogeneousTypeToDisplay; } int totalCopies() { return valuesAndMaybeTypes.totalCopies(); } boolean isEmpty() { return valuesAndMaybeTypes.isEmpty(); } Iterable<Multiset.Entry<?>> entrySet() { return valuesAndMaybeTypes.entrySet(); } @Override public String toString() { return homogeneousTypeToDisplay.isPresent() ? valuesAndMaybeTypes + " (" + homogeneousTypeToDisplay.get() + ")" : valuesAndMaybeTypes.toString(); } } /** * Makes a String representation of {@code items} with additional class info. * * <p>Example: {@code iterableToStringWithTypeInfo([1, 2]) == "[1, 2] (java.lang.Integer)"} and * {@code iterableToStringWithTypeInfo([1, 2L]) == "[1 (java.lang.Integer), 2 (java.lang.Long)]"}. */ static String iterableToStringWithTypeInfo(Iterable<?> itemsIterable) { Collection<?> items = iterableToCollection(itemsIterable); Optional<String> homogeneousTypeName = getHomogeneousTypeName(items); if (homogeneousTypeName.isPresent()) { return lenientFormat("%s (%s)", items, homogeneousTypeName.get()); } else { return addTypeInfoToEveryItem(items).toString(); } } /** * Returns a new collection containing all elements in {@code items} for which there exists at * least one element in {@code itemsToCheck} that has the same {@code toString()} value without * being equal. * * <p>Example: {@code retainMatchingToString([1L, 2L, 2L], [2, 3]) == [2L, 2L]} */ static List<@Nullable Object> retainMatchingToString( Iterable<?> items, Iterable<?> itemsToCheck) {<FILL_FUNCTION_BODY>
ListMultimap<String, @Nullable Object> stringValueToItemsToCheck = ArrayListMultimap.create(); for (Object itemToCheck : itemsToCheck) { stringValueToItemsToCheck.put(String.valueOf(itemToCheck), itemToCheck); } List<@Nullable Object> result = Lists.newArrayList(); for (Object item : items) { for (Object itemToCheck : stringValueToItemsToCheck.get(String.valueOf(item))) { if (!Objects.equal(itemToCheck, item)) { result.add(item); break; } } } return result;
google_truth
truth/core/src/main/java/com/google/common/truth/TableSubject.java
TableSubject
contains
class TableSubject extends Subject { private final @Nullable Table<?, ?, ?> actual; TableSubject(FailureMetadata metadata, @Nullable Table<?, ?, ?> table) { super(metadata, table); this.actual = table; } /** Fails if the table is not empty. */ public void isEmpty() { if (!checkNotNull(actual).isEmpty()) { failWithActual(simpleFact("expected to be empty")); } } /** Fails if the table is empty. */ public void isNotEmpty() { if (checkNotNull(actual).isEmpty()) { failWithoutActual(simpleFact("expected not to be empty")); } } /** Fails if the table does not have the given size. */ public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); check("size()").that(checkNotNull(actual).size()).isEqualTo(expectedSize); } /** Fails if the table does not contain a mapping for the given row key and column key. */ public void contains(@Nullable Object rowKey, @Nullable Object columnKey) {<FILL_FUNCTION_BODY>} /** Fails if the table contains a mapping for the given row key and column key. */ public void doesNotContain(@Nullable Object rowKey, @Nullable Object columnKey) { if (checkNotNull(actual).contains(rowKey, columnKey)) { failWithoutActual( simpleFact("expected not to contain mapping for row-column key pair"), fact("row key", rowKey), fact("column key", columnKey), fact("but contained value", actual.get(rowKey, columnKey)), fact("full contents", actual)); } } /** Fails if the table does not contain the given cell. */ public void containsCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value) { containsCell( Tables.<@Nullable Object, @Nullable Object, @Nullable Object>immutableCell( rowKey, colKey, value)); } /** Fails if the table does not contain the given cell. */ public void containsCell(Cell<?, ?, ?> cell) { checkNotNull(cell); checkNoNeedToDisplayBothValues("cellSet()").that(checkNotNull(actual).cellSet()).contains(cell); } /** Fails if the table contains the given cell. */ public void doesNotContainCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value) { doesNotContainCell( Tables.<@Nullable Object, @Nullable Object, @Nullable Object>immutableCell( rowKey, colKey, value)); } /** Fails if the table contains the given cell. */ public void doesNotContainCell(Cell<?, ?, ?> cell) { checkNotNull(cell); checkNoNeedToDisplayBothValues("cellSet()") .that(checkNotNull(actual).cellSet()) .doesNotContain(cell); } /** Fails if the table does not contain the given row key. */ public void containsRow(@Nullable Object rowKey) { check("rowKeySet()").that(checkNotNull(actual).rowKeySet()).contains(rowKey); } /** Fails if the table does not contain the given column key. */ public void containsColumn(@Nullable Object columnKey) { check("columnKeySet()").that(checkNotNull(actual).columnKeySet()).contains(columnKey); } /** Fails if the table does not contain the given value. */ public void containsValue(@Nullable Object value) { check("values()").that(checkNotNull(actual).values()).contains(value); } }
if (!checkNotNull(actual).contains(rowKey, columnKey)) { /* * TODO(cpovirk): Consider including information about whether any cell with the given row * *or* column was present. */ failWithActual( simpleFact("expected to contain mapping for row-column key pair"), fact("row key", rowKey), fact("column key", columnKey)); }
google_truth
truth/core/src/main/java/com/google/common/truth/ThrowableSubject.java
ThrowableSubject
fillInStackTrace
class ThrowableSubject extends Subject { private final @Nullable Throwable actual; /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call * {@link Subject#check(String, Object...) check(...)}{@code .that(actual)}. */ protected ThrowableSubject(FailureMetadata metadata, @Nullable Throwable throwable) { this(metadata, throwable, null); } ThrowableSubject( FailureMetadata metadata, @Nullable Throwable throwable, @Nullable String typeDescription) { super(metadata, throwable, typeDescription); this.actual = throwable; } /* * TODO(cpovirk): consider a special case for isEqualTo and isSameInstanceAs that adds |expected| * as a suppressed exception */ /** Returns a {@code StringSubject} to make assertions about the throwable's message. */ public final StringSubject hasMessageThat() { StandardSubjectBuilder check = check("getMessage()"); if (actual instanceof ErrorWithFacts && ((ErrorWithFacts) actual).facts().size() > 1) { check = check.withMessage( "(Note from Truth: When possible, instead of asserting on the full message, assert" + " about individual facts by using ExpectFailure.assertThat.)"); } return check.that(checkNotNull(actual).getMessage()); } /** * Returns a new {@code ThrowableSubject} that supports assertions on this throwable's direct * cause. This method can be invoked repeatedly (e.g. {@code * assertThat(e).hasCauseThat().hasCauseThat()....} to assert on a particular indirect cause. */ // Any Throwable is fine, and we use plain Throwable to emphasize that it's not used "for real." @SuppressWarnings("ShouldNotSubclass") public final ThrowableSubject hasCauseThat() { // provides a more helpful error message if hasCauseThat() methods are chained too deep // e.g. assertThat(new Exception()).hCT().hCT().... // TODO(diamondm) in keeping with other subjects' behavior this should still NPE if the subject // *itself* is null, since there's no context to lose. See also b/37645583 if (actual == null) { check("getCause()") .withMessage("Causal chain is not deep enough - add a .isNotNull() check?") .fail(); return ignoreCheck() .that( new Throwable() { @Override @SuppressWarnings("UnsynchronizedOverridesSynchronized") public Throwable fillInStackTrace() {<FILL_FUNCTION_BODY>} }); } return check("getCause()").that(actual.getCause()); } }
setStackTrace(new StackTraceElement[0]); // for old versions of Android return this;
google_truth
truth/core/src/main/java/com/google/common/truth/Truth.java
SimpleAssertionError
createWithNoStack
class SimpleAssertionError extends AssertionError { private SimpleAssertionError(String message, @Nullable Throwable cause) { super(checkNotNull(message)); initCause(cause); } static SimpleAssertionError create(String message, @Nullable Throwable cause) { return new SimpleAssertionError(message, cause); } static SimpleAssertionError createWithNoStack(String message, @Nullable Throwable cause) {<FILL_FUNCTION_BODY>} static SimpleAssertionError createWithNoStack(String message) { return createWithNoStack(message, /* cause= */ null); } @Override public String toString() { return checkNotNull(getLocalizedMessage()); } }
SimpleAssertionError error = create(message, cause); error.setStackTrace(new StackTraceElement[0]); return error;
google_truth
truth/core/src/main/java/com/google/common/truth/TruthFailureSubject.java
TruthFailureSubject
doFactValue
class TruthFailureSubject extends ThrowableSubject { static final Fact HOW_TO_TEST_KEYS_WITHOUT_VALUES = simpleFact( "To test that a key is present without a value, " + "use factKeys().contains(...) or a similar method."); /** * Factory for creating {@link TruthFailureSubject} instances. Most users will just use {@link * ExpectFailure#assertThat}. */ public static Factory<TruthFailureSubject, AssertionError> truthFailures() { return FACTORY; } private static final Factory<TruthFailureSubject, AssertionError> FACTORY = new Factory<TruthFailureSubject, AssertionError>() { @Override public TruthFailureSubject createSubject( FailureMetadata metadata, @Nullable AssertionError actual) { return new TruthFailureSubject(metadata, actual, "failure"); } }; private final @Nullable AssertionError actual; TruthFailureSubject( FailureMetadata metadata, @Nullable AssertionError actual, @Nullable String typeDescription) { super(metadata, actual, typeDescription); this.actual = actual; } /** Returns a subject for the list of fact keys. */ public IterableSubject factKeys() { if (!(actual instanceof ErrorWithFacts)) { failWithActual(simpleFact("expected a failure thrown by Truth's failure API")); return ignoreCheck().that(ImmutableList.of()); } ErrorWithFacts error = (ErrorWithFacts) actual; return check("factKeys()").that(getFactKeys(error)); } private static ImmutableList<String> getFactKeys(ErrorWithFacts error) { ImmutableList.Builder<String> facts = ImmutableList.builder(); for (Fact fact : error.facts()) { facts.add(fact.key); } return facts.build(); } /** * Returns a subject for the value with the given name. * * <p>The value is always a string, the {@code String.valueOf} representation of the value passed * to {@link Fact#fact}. * * <p>The value is never null: * * <ul> * <li>In the case of {@linkplain Fact#simpleFact facts that have no value}, {@code factValue} * throws an exception. To test for such facts, use {@link #factKeys()}{@code * .contains(...)} or a similar method. * <li>In the case of facts that have a value that is rendered as "null" (such as those created * with {@code fact("key", null)}), {@code factValue} considers them have a string value, * the string "null." * </ul> * * <p>If the failure under test contains more than one fact with the given key, this method will * fail the test. To assert about such a failure, use {@linkplain #factValue(String, int) the * other overload} of {@code factValue}. */ public StringSubject factValue(String key) { return doFactValue(key, null); } /** * Returns a subject for the value of the {@code index}-th instance of the fact with the given * name. Most Truth failures do not contain multiple facts with the same key, so most tests should * use {@linkplain #factValue(String) the other overload} of {@code factValue}. */ public StringSubject factValue(String key, int index) { checkArgument(index >= 0, "index must be nonnegative: %s", index); return doFactValue(key, index); } private StringSubject doFactValue(String key, @Nullable Integer index) {<FILL_FUNCTION_BODY>} private static ImmutableList<Fact> factsWithName(ErrorWithFacts error, String key) { ImmutableList.Builder<Fact> facts = ImmutableList.builder(); for (Fact fact : error.facts()) { if (fact.key.equals(key)) { facts.add(fact); } } return facts.build(); } }
checkNotNull(key); if (!(actual instanceof ErrorWithFacts)) { failWithActual(simpleFact("expected a failure thrown by Truth's failure API")); return ignoreCheck().that(""); } ErrorWithFacts error = (ErrorWithFacts) actual; /* * We don't care as much about including the actual AssertionError and its facts in these * because the AssertionError will be attached as a cause in nearly all cases. */ ImmutableList<Fact> factsWithName = factsWithName(error, key); if (factsWithName.isEmpty()) { failWithoutActual( fact("expected to contain fact", key), fact("but contained only", getFactKeys(error))); return ignoreCheck().that(""); } if (index == null && factsWithName.size() > 1) { failWithoutActual( fact("expected to contain a single fact with key", key), fact("but contained multiple", factsWithName)); return ignoreCheck().that(""); } if (index != null && index > factsWithName.size()) { failWithoutActual( fact("for key", key), fact("index too high", index), fact("fact count was", factsWithName.size())); return ignoreCheck().that(""); } String value = factsWithName.get(firstNonNull(index, 0)).value; if (value == null) { if (index == null) { failWithoutActual( simpleFact("expected to have a value"), fact("for key", key), simpleFact("but the key was present with no value"), HOW_TO_TEST_KEYS_WITHOUT_VALUES); } else { failWithoutActual( simpleFact("expected to have a value"), fact("for key", key), fact("and index", index), simpleFact("but the key was present with no value"), HOW_TO_TEST_KEYS_WITHOUT_VALUES); } return ignoreCheck().that(""); } StandardSubjectBuilder check = index == null ? check("factValue(%s)", key) : check("factValue(%s, %s)", key, index); return check.that(value);
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/AnyUtils.java
AnyUtils
unpack
class AnyUtils { private static final FieldDescriptor TYPE_URL_FIELD_DESCRIPTOR = Any.getDescriptor().findFieldByNumber(Any.TYPE_URL_FIELD_NUMBER); static FieldDescriptor typeUrlFieldDescriptor() { return TYPE_URL_FIELD_DESCRIPTOR; } private static final SubScopeId TYPE_URL_SUB_SCOPE_ID = SubScopeId.of(TYPE_URL_FIELD_DESCRIPTOR); static SubScopeId typeUrlSubScopeId() { return TYPE_URL_SUB_SCOPE_ID; } private static final FieldDescriptor VALUE_FIELD_DESCRIPTOR = Any.getDescriptor().findFieldByNumber(Any.VALUE_FIELD_NUMBER); static FieldDescriptor valueFieldDescriptor() { return VALUE_FIELD_DESCRIPTOR; } private static final SubScopeId VALUE_SUB_SCOPE_ID = SubScopeId.of(VALUE_FIELD_DESCRIPTOR); static SubScopeId valueSubScopeId() { return VALUE_SUB_SCOPE_ID; } private static final TypeRegistry DEFAULT_TYPE_REGISTRY = TypeRegistry.getEmptyTypeRegistry(); static TypeRegistry defaultTypeRegistry() { return DEFAULT_TYPE_REGISTRY; } private static final ExtensionRegistry DEFAULT_EXTENSION_REGISTRY = ExtensionRegistry.getEmptyRegistry(); static ExtensionRegistry defaultExtensionRegistry() { return DEFAULT_EXTENSION_REGISTRY; } /** Unpack an `Any` proto using the given TypeRegistry and ExtensionRegistry. */ static Optional<Message> unpack( Message any, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) {<FILL_FUNCTION_BODY>} private AnyUtils() {} }
Preconditions.checkArgument( any.getDescriptorForType().equals(Any.getDescriptor()), "Expected type google.protobuf.Any, but was: %s", any.getDescriptorForType().getFullName()); String typeUrl = (String) any.getField(typeUrlFieldDescriptor()); ByteString value = (ByteString) any.getField(valueFieldDescriptor()); try { Descriptor descriptor = typeRegistry.getDescriptorForTypeUrl(typeUrl); if (descriptor == null) { return Optional.absent(); } Message defaultMessage = DynamicMessage.parseFrom(descriptor, value, extensionRegistry); return Optional.of(defaultMessage); } catch (InvalidProtocolBufferException e) { return Optional.absent(); }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/DiffResult.java
SingularField
printContents
class SingularField extends RecursableDiffEntity.WithResultCode implements ProtoPrintable { /** The type information for this field. May be absent if result code is {@code IGNORED}. */ abstract Optional<SubScopeId> subScopeId(); /** The display name for this field. May include an array-index specifier. */ abstract String fieldName(); /** The field under test. */ abstract Optional<Object> actual(); /** The expected value of said field. */ abstract Optional<Object> expected(); /** * The detailed breakdown of the comparison, only present if both objects are set on this * instance and they are messages. * * <p>This does not necessarily mean the messages were set on the input protos. */ abstract Optional<DiffResult> breakdown(); /** * The detailed breakdown of the comparison, only present if both objects are set and they are * {@link UnknownFieldSet}s. * * <p>This will only ever be set inside a parent {@link UnknownFieldSetDiff}. The top {@link * UnknownFieldSetDiff} is set on the {@link DiffResult}, not here. */ abstract Optional<UnknownFieldSetDiff> unknownsBreakdown(); /** Returns {@code actual().get()}, or {@code expected().get()}, whichever is available. */ @Memoized Object actualOrExpected() { return actual().or(expected()).get(); } @Memoized @Override Iterable<? extends RecursableDiffEntity> childEntities() { return ImmutableList.copyOf( Iterables.concat(breakdown().asSet(), unknownsBreakdown().asSet())); } @Override final void printContents(boolean includeMatches, String fieldPrefix, StringBuilder sb) {<FILL_FUNCTION_BODY>} @Override final boolean isContentEmpty() { return false; } static SingularField ignored(String fieldName) { return newBuilder() .setFieldName(fieldName) .setResult(Result.IGNORED) // Ignored fields don't need a customized proto printer. .setProtoPrinter(TextFormat.printer()) .build(); } static Builder newBuilder() { return new AutoValue_DiffResult_SingularField.Builder(); } /** Builder for {@link SingularField}. */ @AutoValue.Builder abstract static class Builder { abstract Builder setResult(Result result); abstract Builder setSubScopeId(SubScopeId subScopeId); abstract Builder setFieldName(String fieldName); abstract Builder setActual(Object actual); abstract Builder setExpected(Object expected); abstract Builder setBreakdown(DiffResult breakdown); abstract Builder setUnknownsBreakdown(UnknownFieldSetDiff unknownsBreakdown); abstract Builder setProtoPrinter(TextFormat.Printer value); abstract SingularField build(); } }
if (!includeMatches && isMatched()) { return; } fieldPrefix = newFieldPrefix(fieldPrefix, fieldName()); switch (result()) { case ADDED: sb.append("added: ").append(fieldPrefix).append(": "); if (actual().get() instanceof Message) { sb.append("\n"); printMessage((Message) actual().get(), sb); } else { printFieldValue(subScopeId().get(), actual().get(), sb); sb.append("\n"); } return; case IGNORED: sb.append("ignored: ").append(fieldPrefix).append("\n"); return; case MATCHED: sb.append("matched: ").append(fieldPrefix); if (actualOrExpected() instanceof Message) { sb.append("\n"); printChildContents(includeMatches, fieldPrefix, sb); } else { sb.append(": "); printFieldValue(subScopeId().get(), actualOrExpected(), sb); sb.append("\n"); } return; case MODIFIED: sb.append("modified: ").append(fieldPrefix); if (actualOrExpected() instanceof Message) { sb.append("\n"); printChildContents(includeMatches, fieldPrefix, sb); } else { sb.append(": "); printFieldValue(subScopeId().get(), expected().get(), sb); sb.append(" -> "); printFieldValue(subScopeId().get(), actual().get(), sb); sb.append("\n"); } return; case REMOVED: sb.append("deleted: ").append(fieldPrefix).append(": "); if (expected().get() instanceof Message) { sb.append("\n"); printMessage((Message) expected().get(), sb); } else { printFieldValue(subScopeId().get(), expected().get(), sb); sb.append("\n"); } return; default: throw new AssertionError("Impossible: " + result()); }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldNumberTree.java
FieldNumberTree
fromMessage
class FieldNumberTree { private static final FieldNumberTree EMPTY = new FieldNumberTree(); /** A {@code FieldNumberTree} with no children. */ static FieldNumberTree empty() { return EMPTY; } // Modified only during [factory] construction, never changed afterwards. private final Map<SubScopeId, FieldNumberTree> children = Maps.newHashMap(); /** Returns whether this {@code FieldNumberTree} has no children. */ boolean isEmpty() { return children.isEmpty(); } /** * Returns the {@code FieldNumberTree} corresponding to this sub-field. * * <p>{@code empty()} if there is none. */ FieldNumberTree child(SubScopeId subScopeId) { FieldNumberTree child = children.get(subScopeId); return child == null ? EMPTY : child; } /** Returns whether this tree has a child for this node. */ boolean hasChild(SubScopeId subScopeId) { return children.containsKey(subScopeId); } static FieldNumberTree fromMessage( Message message, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) {<FILL_FUNCTION_BODY>} static FieldNumberTree fromMessages( Iterable<? extends Message> messages, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { FieldNumberTree tree = new FieldNumberTree(); for (Message message : messages) { if (message != null) { tree.merge(fromMessage(message, typeRegistry, extensionRegistry)); } } return tree; } private static FieldNumberTree fromUnknownFieldSet(UnknownFieldSet unknownFieldSet) { FieldNumberTree tree = new FieldNumberTree(); for (int fieldNumber : unknownFieldSet.asMap().keySet()) { UnknownFieldSet.Field unknownField = unknownFieldSet.asMap().get(fieldNumber); for (UnknownFieldDescriptor unknownFieldDescriptor : UnknownFieldDescriptor.descriptors(fieldNumber, unknownField)) { SubScopeId subScopeId = SubScopeId.of(unknownFieldDescriptor); FieldNumberTree childTree = new FieldNumberTree(); tree.children.put(subScopeId, childTree); if (unknownFieldDescriptor.type() == UnknownFieldDescriptor.Type.GROUP) { for (Object group : unknownFieldDescriptor.type().getValues(unknownField)) { childTree.merge(fromUnknownFieldSet((UnknownFieldSet) group)); } } } } return tree; } /** Adds the other tree onto this one. May destroy {@code other} in the process. */ private void merge(FieldNumberTree other) { for (SubScopeId subScopeId : other.children.keySet()) { FieldNumberTree value = other.children.get(subScopeId); if (!this.children.containsKey(subScopeId)) { this.children.put(subScopeId, value); } else { this.children.get(subScopeId).merge(value); } } } }
FieldNumberTree tree = new FieldNumberTree(); // Known fields. Map<FieldDescriptor, Object> knownFieldValues = message.getAllFields(); for (FieldDescriptor field : knownFieldValues.keySet()) { SubScopeId subScopeId = SubScopeId.of(field); FieldNumberTree childTree = new FieldNumberTree(); tree.children.put(subScopeId, childTree); if (field.equals(AnyUtils.valueFieldDescriptor())) { // Handle Any protos specially. Optional<Message> unpackedAny = AnyUtils.unpack(message, typeRegistry, extensionRegistry); if (unpackedAny.isPresent()) { tree.children.put( SubScopeId.ofUnpackedAnyValueType(unpackedAny.get().getDescriptorForType()), fromMessage(unpackedAny.get(), typeRegistry, extensionRegistry)); } } else { Object fieldValue = knownFieldValues.get(field); if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { List<?> valueList = (List<?>) fieldValue; for (Object value : valueList) { childTree.merge(fromMessage((Message) value, typeRegistry, extensionRegistry)); } } else { childTree.merge(fromMessage((Message) fieldValue, typeRegistry, extensionRegistry)); } } } } // Unknown fields. tree.merge(fromUnknownFieldSet(message.getUnknownFields())); return tree;
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeImpl.java
FieldScopeImpl
getDescriptors
class FieldScopeImpl extends FieldScope { ////////////////////////////////////////////////////////////////////////////////////////////////// // AutoValue methods. ////////////////////////////////////////////////////////////////////////////////////////////////// private static FieldScope create( FieldScopeLogic logic, Function<? super Optional<Descriptor>, String> usingCorrespondenceStringFunction) { return new AutoValue_FieldScopeImpl(logic, usingCorrespondenceStringFunction); } @Override abstract FieldScopeLogic logic(); abstract Function<? super Optional<Descriptor>, String> usingCorrespondenceStringFunction(); ////////////////////////////////////////////////////////////////////////////////////////////////// // Instantiation methods. ////////////////////////////////////////////////////////////////////////////////////////////////// static FieldScope createFromSetFields( Message message, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { return create( FieldScopeLogic.partialScope(message, typeRegistry, extensionRegistry), Functions.constant(String.format("FieldScopes.fromSetFields({%s})", message.toString()))); } static FieldScope createFromSetFields( Iterable<? extends Message> messages, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { if (emptyOrAllNull(messages)) { return create( FieldScopeLogic.none(), Functions.constant(String.format("FieldScopes.fromSetFields(%s)", messages.toString()))); } Optional<Descriptor> optDescriptor = FieldScopeUtil.getSingleDescriptor(messages); checkArgument( optDescriptor.isPresent(), "Cannot create scope from messages with different descriptors: %s", getDescriptors(messages)); return create( FieldScopeLogic.partialScope( messages, optDescriptor.get(), typeRegistry, extensionRegistry), Functions.constant(String.format("FieldScopes.fromSetFields(%s)", formatList(messages)))); } static FieldScope createIgnoringFields(Iterable<Integer> fieldNumbers) { return create( FieldScopeLogic.all().ignoringFields(fieldNumbers), FieldScopeUtil.fieldNumbersFunction("FieldScopes.ignoringFields(%s)", fieldNumbers)); } static FieldScope createIgnoringFieldDescriptors(Iterable<FieldDescriptor> fieldDescriptors) { return create( FieldScopeLogic.all().ignoringFieldDescriptors(fieldDescriptors), Functions.constant( String.format("FieldScopes.ignoringFieldDescriptors(%s)", join(fieldDescriptors)))); } static FieldScope createAllowingFields(Iterable<Integer> fieldNumbers) { return create( FieldScopeLogic.none().allowingFields(fieldNumbers), FieldScopeUtil.fieldNumbersFunction("FieldScopes.allowingFields(%s)", fieldNumbers)); } static FieldScope createAllowingFieldDescriptors(Iterable<FieldDescriptor> fieldDescriptors) { return create( FieldScopeLogic.none().allowingFieldDescriptors(fieldDescriptors), Functions.constant( String.format("FieldScopes.allowingFieldDescriptors(%s)", join(fieldDescriptors)))); } private static final FieldScope ALL = create(FieldScopeLogic.all(), Functions.constant("FieldScopes.all()")); private static final FieldScope NONE = create(FieldScopeLogic.none(), Functions.constant("FieldScopes.none()")); static FieldScope all() { return ALL; } static FieldScope none() { return NONE; } private static boolean emptyOrAllNull(Iterable<?> objects) { for (Object object : objects) { if (object != null) { return false; } } return true; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Delegation methods. ////////////////////////////////////////////////////////////////////////////////////////////////// @Override String usingCorrespondenceString(Optional<Descriptor> descriptor) { return usingCorrespondenceStringFunction().apply(descriptor); } @Override public final FieldScope ignoringFields(int firstFieldNumber, int... rest) { return ignoringFields(asList(firstFieldNumber, rest)); } @Override public final FieldScope ignoringFields(Iterable<Integer> fieldNumbers) { return create( logic().ignoringFields(fieldNumbers), addUsingCorrespondenceFieldNumbersString(".ignoringFields(%s)", fieldNumbers)); } @Override public final FieldScope ignoringFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return ignoringFieldDescriptors(asList(firstFieldDescriptor, rest)); } @Override public final FieldScope ignoringFieldDescriptors(Iterable<FieldDescriptor> fieldDescriptors) { return create( logic().ignoringFieldDescriptors(fieldDescriptors), addUsingCorrespondenceFieldDescriptorsString( ".ignoringFieldDescriptors(%s)", fieldDescriptors)); } @Override public final FieldScope allowingFields(int firstFieldNumber, int... rest) { return allowingFields(asList(firstFieldNumber, rest)); } @Override public final FieldScope allowingFields(Iterable<Integer> fieldNumbers) { return create( logic().allowingFields(fieldNumbers), addUsingCorrespondenceFieldNumbersString(".allowingFields(%s)", fieldNumbers)); } @Override public final FieldScope allowingFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return allowingFieldDescriptors(asList(firstFieldDescriptor, rest)); } @Override public final FieldScope allowingFieldDescriptors(Iterable<FieldDescriptor> fieldDescriptors) { return create( logic().allowingFieldDescriptors(fieldDescriptors), addUsingCorrespondenceFieldDescriptorsString( ".allowingFieldDescriptors(%s)", fieldDescriptors)); } private Function<Optional<Descriptor>, String> addUsingCorrespondenceFieldNumbersString( String fmt, Iterable<Integer> fieldNumbers) { return FieldScopeUtil.concat( usingCorrespondenceStringFunction(), FieldScopeUtil.fieldNumbersFunction(fmt, fieldNumbers)); } private Function<Optional<Descriptor>, String> addUsingCorrespondenceFieldDescriptorsString( String fmt, Iterable<FieldDescriptor> fieldDescriptors) { return FieldScopeUtil.concat( usingCorrespondenceStringFunction(), Functions.constant(String.format(fmt, join(fieldDescriptors)))); } private static Iterable<String> getDescriptors(Iterable<? extends Message> messages) {<FILL_FUNCTION_BODY>} private static String formatList(Iterable<? extends Message> messages) { List<String> strings = Lists.newArrayList(); for (Message message : messages) { strings.add(message == null ? "null" : "{" + message + "}"); } return "[" + join(strings) + "]"; } }
List<String> descriptors = Lists.newArrayList(); for (Message message : messages) { descriptors.add(message == null ? "null" : message.getDescriptorForType().getFullName()); } return descriptors;
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogic.java
IntersectionFieldScopeLogic
intersection
class IntersectionFieldScopeLogic extends CompoundFieldScopeLogic<IntersectionFieldScopeLogic> { IntersectionFieldScopeLogic(FieldScopeLogic subject1, FieldScopeLogic subject2) { super(subject1, subject2); } @Override IntersectionFieldScopeLogic newLogicOfSameType(List<FieldScopeLogic> newElements) { checkArgument(newElements.size() == 2, "Expected 2 elements: %s", newElements); return new IntersectionFieldScopeLogic(newElements.get(0), newElements.get(1)); } @Override FieldScopeResult policyFor(Descriptor rootDescriptor, SubScopeId subScopeId) { // The intersection of two scopes is ignorable if either scope is itself ignorable. return intersection( elements.get(0).policyFor(rootDescriptor, subScopeId), elements.get(1).policyFor(rootDescriptor, subScopeId)); } private static FieldScopeResult intersection( FieldScopeResult result1, FieldScopeResult result2) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("(%s && %s)", elements.get(0), elements.get(1)); } }
if (result1 == FieldScopeResult.EXCLUDED_RECURSIVELY || result2 == FieldScopeResult.EXCLUDED_RECURSIVELY) { // If either argument is excluded recursively, the result is too. return FieldScopeResult.EXCLUDED_RECURSIVELY; } else if (!result1.included() || !result2.included()) { // Otherwise, we exclude non-recursively if either result is an exclusion. return FieldScopeResult.EXCLUDED_NONRECURSIVELY; } else if (result1.recursive() && result2.recursive()) { // We include recursively if both arguments are recursive. return FieldScopeResult.INCLUDED_RECURSIVELY; } else { // Otherwise, we include non-recursively. return FieldScopeResult.INCLUDED_NONRECURSIVELY; }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java
Entry
validate
class Entry<V> { abstract FieldScopeLogic fieldScopeLogic(); abstract V value(); static <V> Entry<V> of(FieldScopeLogic fieldScopeLogic, V value) { return new AutoValue_FieldScopeLogicMap_Entry<>(fieldScopeLogic, value); } } private static final FieldScopeLogicMap<Object> EMPTY_INSTANCE = new FieldScopeLogicMap<>(ImmutableList.<Entry<Object>>of()); // Key -> value mappings for this map. Earlier entries override later ones. private final ImmutableList<Entry<V>> entries; private FieldScopeLogicMap(Iterable<Entry<V>> entries) { this.entries = ImmutableList.copyOf(entries); } public boolean isEmpty() { return entries.isEmpty(); } public Optional<V> get(Descriptor rootDescriptor, SubScopeId subScopeId) { // Earlier entries override later ones, so we don't need to iterate backwards. for (Entry<V> entry : entries) { if (entry.fieldScopeLogic().contains(rootDescriptor, subScopeId)) { return Optional.of(entry.value()); } } return Optional.absent(); } /** Returns a new immutable map that adds the given fields -> value mapping. */ public FieldScopeLogicMap<V> with(FieldScopeLogic fieldScopeLogic, V value) { ImmutableList.Builder<Entry<V>> newEntries = ImmutableList.builder(); // Earlier entries override later ones, so we insert the new one at the front of the list. newEntries.add(Entry.of(fieldScopeLogic, value)); newEntries.addAll(entries); return new FieldScopeLogicMap<>(newEntries.build()); } @Override public FieldScopeLogicMap<V> subScope(Descriptor rootDescriptor, SubScopeId subScopeId) { ImmutableList.Builder<Entry<V>> newEntries = ImmutableList.builderWithExpectedSize(entries.size()); for (Entry<V> entry : entries) { newEntries.add( Entry.of(entry.fieldScopeLogic().subScope(rootDescriptor, subScopeId), entry.value())); } return new FieldScopeLogicMap<>(newEntries.build()); } @Override public void validate( Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) {<FILL_FUNCTION_BODY>
for (Entry<V> entry : entries) { entry.fieldScopeLogic().validate(rootDescriptor, fieldDescriptorValidator); }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java
FieldScopeUtil
resolveFieldNumbers
class FieldScopeUtil { /** * Returns a function which translates integer field numbers into field names using the Descriptor * if available. * * @param fmt Format string that must contain exactly one '%s' and no other format parameters. */ static Function<Optional<Descriptor>, String> fieldNumbersFunction( String fmt, Iterable<Integer> fieldNumbers) { return optDescriptor -> resolveFieldNumbers(optDescriptor, fmt, fieldNumbers); } /** * Returns a function which formats the given string by getting the usingCorrespondenceString from * the given FieldScope with the argument descriptor. * * @param fmt Format string that must contain exactly one '%s' and no other format parameters. */ static Function<Optional<Descriptor>, String> fieldScopeFunction( String fmt, FieldScope fieldScope) { return optDescriptor -> String.format(fmt, fieldScope.usingCorrespondenceString(optDescriptor)); } /** Returns a function which concatenates the outputs of the two input functions. */ static Function<Optional<Descriptor>, String> concat( Function<? super Optional<Descriptor>, String> function1, Function<? super Optional<Descriptor>, String> function2) { return optDescriptor -> function1.apply(optDescriptor) + function2.apply(optDescriptor); } /** * Returns the singular descriptor used by all non-null messages in the list. * * <p>If there is no descriptor, or more than one, returns {@code Optional.absent()}. */ static Optional<Descriptor> getSingleDescriptor(Iterable<? extends Message> messages) { Optional<Descriptor> optDescriptor = Optional.absent(); for (Message message : messages) { if (message != null) { Descriptor descriptor = message.getDescriptorForType(); if (!optDescriptor.isPresent()) { optDescriptor = Optional.of(descriptor); } else if (descriptor != optDescriptor.get()) { // Two different descriptors - abandon ship. return Optional.absent(); } } } return optDescriptor; } /** Joins the arguments into a {@link List} for convenience. */ static List<Integer> asList(int first, int... rest) { List<Integer> list = Lists.newArrayList(); list.add(first); list.addAll(Ints.asList(rest)); return list; } private static final Joiner JOINER = Joiner.on(", "); static String join(Iterable<?> objects) { return JOINER.join(objects); } /** * Formats {@code fmt} with the field numbers, concatenated, if a descriptor is available to * resolve them to field names. Otherwise it uses the raw integers. * * @param fmt Format string that must contain exactly one '%s' and no other format parameters. */ private static String resolveFieldNumbers( Optional<Descriptor> optDescriptor, String fmt, Iterable<Integer> fieldNumbers) {<FILL_FUNCTION_BODY>} private FieldScopeUtil() {} }
if (optDescriptor.isPresent()) { Descriptor descriptor = optDescriptor.get(); List<String> strings = Lists.newArrayList(); for (int fieldNumber : fieldNumbers) { FieldDescriptor field = descriptor.findFieldByNumber(fieldNumber); strings.add(field != null ? field.toString() : String.format("%d (?)", fieldNumber)); } return String.format(fmt, join(strings)); } else { return String.format(fmt, join(fieldNumbers)); }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/IterableOfProtosSubject.java
UsingCorrespondence
delegate
class UsingCorrespondence<M extends Message> implements IterableOfProtosUsingCorrespondence<M> { private final IterableOfProtosSubject<M> subject; private final @Nullable Function<? super M, ? extends Object> keyFunction; UsingCorrespondence( IterableOfProtosSubject<M> subject, @Nullable Function<? super M, ? extends Object> keyFunction) { this.subject = checkNotNull(subject); this.keyFunction = keyFunction; } private IterableSubject.UsingCorrespondence<M, M> delegate(Iterable<? extends M> messages) {<FILL_FUNCTION_BODY>} @Override public IterableOfProtosUsingCorrespondence<M> displayingDiffsPairedBy( Function<? super M, ?> keyFunction) { return new UsingCorrespondence<M>(subject, checkNotNull(keyFunction)); } @Override public void contains(@Nullable M expected) { delegate(Arrays.asList(expected)).contains(expected); } @Override public void doesNotContain(@Nullable M excluded) { delegate(Arrays.asList(excluded)).doesNotContain(excluded); } @Override @CanIgnoreReturnValue public Ordered containsExactly(@Nullable M... expected) { return delegate(Arrays.asList(expected)).containsExactly(expected); } @Override @CanIgnoreReturnValue public Ordered containsExactlyElementsIn(Iterable<? extends M> expected) { return delegate(expected).containsExactlyElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsExactlyElementsIn(M[] expected) { return delegate(Arrays.asList(expected)).containsExactlyElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsAtLeast(@Nullable M first, @Nullable M second, @Nullable M... rest) { return delegate(Lists.asList(first, second, rest)).containsAtLeast(first, second, rest); } @Override @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn(Iterable<? extends M> expected) { return delegate(expected).containsAtLeastElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn(M[] expected) { return delegate(Arrays.asList(expected)).containsAtLeastElementsIn(expected); } @Override public void containsAnyOf(@Nullable M first, @Nullable M second, @Nullable M... rest) { delegate(Lists.asList(first, second, rest)).containsAnyOf(first, second, rest); } @Override public void containsAnyIn(Iterable<? extends M> expected) { delegate(expected).containsAnyIn(expected); } @Override public void containsAnyIn(M[] expected) { delegate(Arrays.asList(expected)).containsAnyIn(expected); } @Override public void containsNoneOf( @Nullable M firstExcluded, @Nullable M secondExcluded, @Nullable M... restOfExcluded) { delegate(Lists.asList(firstExcluded, secondExcluded, restOfExcluded)) .containsNoneOf(firstExcluded, secondExcluded, restOfExcluded); } @Override public void containsNoneIn(Iterable<? extends M> excluded) { delegate(excluded).containsNoneIn(excluded); } @Override public void containsNoneIn(M[] excluded) { delegate(Arrays.asList(excluded)).containsNoneIn(excluded); } }
IterableSubject.UsingCorrespondence<M, M> usingCorrespondence = subject.comparingElementsUsing( subject .config .withExpectedMessages(messages) .<M>toCorrespondence(FieldScopeUtil.getSingleDescriptor(subject.actual))); if (keyFunction != null) { usingCorrespondence = usingCorrespondence.displayingDiffsPairedBy(keyFunction); } return usingCorrespondence;
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/RecursableDiffEntity.java
RecursableDiffEntity
isAnyChildMatched
class RecursableDiffEntity { // Lazily-initialized return values for the recursive properties of the entity. // null = not initialized yet // // This essentially implements what @Memoized does, but @AutoValue doesn't support @Memoized on // parent classes. I think it's better to roll-our-own in the parent class to take advantage of // inheritance, than to duplicate the @Memoized methods for every subclass. private Boolean isAnyChildIgnored = null; private Boolean isAnyChildMatched = null; // Only extended by inner classes. private RecursableDiffEntity() {} /** * The children of this entity. May be empty. * * <p>Subclasses should {@link @Memoized} this method especially if it's expensive. */ abstract Iterable<? extends RecursableDiffEntity> childEntities(); /** Returns whether or not the two entities matched according to the diff rules. */ abstract boolean isMatched(); /** Returns true if all sub-fields of both entities were ignored for comparison. */ abstract boolean isIgnored(); /** * Returns true if some child entity matched. * * <p>Caches the result for future calls. */ final boolean isAnyChildMatched() {<FILL_FUNCTION_BODY>} /** * Returns true if some child entity was ignored. * * <p>Caches the result for future calls. */ final boolean isAnyChildIgnored() { if (isAnyChildIgnored == null) { isAnyChildIgnored = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isIgnored() && !entity.isContentEmpty()) || entity.isAnyChildIgnored()) { isAnyChildIgnored = true; break; } } } return isAnyChildIgnored; } /** * Prints the contents of this diff entity to {@code sb}. * * @param includeMatches Whether to include reports for fields which matched. * @param fieldPrefix The human-readable field path leading to this entity. Empty if this is the * root entity. * @param sb Builder to print the text to. */ abstract void printContents(boolean includeMatches, String fieldPrefix, StringBuilder sb); /** Returns true if this entity has no contents to print, with or without includeMatches. */ abstract boolean isContentEmpty(); final void printChildContents(boolean includeMatches, String fieldPrefix, StringBuilder sb) { for (RecursableDiffEntity entity : childEntities()) { entity.printContents(includeMatches, fieldPrefix, sb); } } /** * A generic entity in the {@link DiffResult} tree without a result code. * * <p>This entity derives its {@code isMatched()} and {@code isIgnored()} state purely from its * children. If it has no children, it is considered both matched and ignored. */ abstract static class WithoutResultCode extends RecursableDiffEntity { private Boolean isMatched = null; private Boolean isIgnored = null; @Override final boolean isMatched() { if (isMatched == null) { isMatched = true; for (RecursableDiffEntity entity : childEntities()) { if (!entity.isMatched()) { isMatched = false; break; } } } return isMatched; } @Override final boolean isIgnored() { if (isIgnored == null) { isIgnored = true; for (RecursableDiffEntity entity : childEntities()) { if (!entity.isIgnored()) { isIgnored = false; break; } } } return isIgnored; } } /** * A generic entity in the {@link DiffResult} tree with a result code. * * <p>The result code overrides {@code isMatched()} and {@code isIgnored()} evaluation, using the * provided enum instead of any child states. */ abstract static class WithResultCode extends RecursableDiffEntity { enum Result { /** No differences. The expected case. */ MATCHED, /** expected() didn't have this field, actual() did. */ ADDED, /** actual() didn't have this field, expected() did. */ REMOVED, /** Both messages had the field but the values don't match. */ MODIFIED, /** * The message was moved from one index to another, but strict ordering was expected. * * <p>This is only possible on {@link DiffResult.RepeatedField.PairResult}. */ MOVED_OUT_OF_ORDER, /** * The messages were ignored for the sake of comparison. * * <p>IGNORED fields should also be considered MATCHED, for the sake of pass/fail decisions. * The IGNORED information is useful for limiting diff output: i.e., if all fields in a deep * submessage-to-submessage comparison are ignored, we can print the top-level type as ignored * and omit diff lines for the rest of the fields within. */ IGNORED; static Builder builder() { return new Builder(); } /** * A helper class for computing a {@link Result}. It defaults to {@code MATCHED}, but can be * changed exactly once if called with a true {@code condition}. * * <p>All subsequent 'mark' calls after a successful mark are ignored. */ static final class Builder { private Result state = Result.MATCHED; private Builder() {} public void markAddedIf(boolean condition) { setIf(condition, Result.ADDED); } public void markRemovedIf(boolean condition) { setIf(condition, Result.REMOVED); } public void markModifiedIf(boolean condition) { setIf(condition, Result.MODIFIED); } public Result build() { return state; } private void setIf(boolean condition, Result newState) { if (condition && state == Result.MATCHED) { state = newState; } } } } abstract Result result(); @Override final boolean isMatched() { return result() == Result.MATCHED || result() == Result.IGNORED; } @Override final boolean isIgnored() { return result() == Result.IGNORED; } } }
if (isAnyChildMatched == null) { isAnyChildMatched = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isMatched() && !entity.isContentEmpty()) || entity.isAnyChildMatched()) { isAnyChildMatched = true; break; } } } return isAnyChildMatched;
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/SubScopeId.java
SubScopeId
shortName
class SubScopeId { enum Kind { FIELD_DESCRIPTOR, UNKNOWN_FIELD_DESCRIPTOR, UNPACKED_ANY_VALUE_TYPE; } abstract Kind kind(); abstract FieldDescriptor fieldDescriptor(); abstract UnknownFieldDescriptor unknownFieldDescriptor(); abstract Descriptor unpackedAnyValueType(); /** Returns a short, human-readable version of this identifier. */ final String shortName() {<FILL_FUNCTION_BODY>} static SubScopeId of(FieldDescriptor fieldDescriptor) { return AutoOneOf_SubScopeId.fieldDescriptor(fieldDescriptor); } static SubScopeId of(UnknownFieldDescriptor unknownFieldDescriptor) { return AutoOneOf_SubScopeId.unknownFieldDescriptor(unknownFieldDescriptor); } static SubScopeId ofUnpackedAnyValueType(Descriptor unpackedAnyValueType) { return AutoOneOf_SubScopeId.unpackedAnyValueType(unpackedAnyValueType); } }
switch (kind()) { case FIELD_DESCRIPTOR: return fieldDescriptor().isExtension() ? "[" + fieldDescriptor() + "]" : fieldDescriptor().getName(); case UNKNOWN_FIELD_DESCRIPTOR: return String.valueOf(unknownFieldDescriptor().fieldNumber()); case UNPACKED_ANY_VALUE_TYPE: return AnyUtils.valueFieldDescriptor().getName(); } throw new AssertionError(kind());
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/UnknownFieldDescriptor.java
UnknownFieldDescriptor
descriptors
class UnknownFieldDescriptor { enum Type { VARINT(WireFormat.WIRETYPE_VARINT) { @Override public List<?> getValues(UnknownFieldSet.Field field) { return field.getVarintList(); } }, FIXED32(WireFormat.WIRETYPE_FIXED32) { @Override public List<?> getValues(UnknownFieldSet.Field field) { return field.getFixed32List(); } }, FIXED64(WireFormat.WIRETYPE_FIXED64) { @Override public List<?> getValues(UnknownFieldSet.Field field) { return field.getFixed64List(); } }, LENGTH_DELIMITED(WireFormat.WIRETYPE_LENGTH_DELIMITED) { @Override public List<?> getValues(UnknownFieldSet.Field field) { return field.getLengthDelimitedList(); } }, GROUP(WireFormat.WIRETYPE_START_GROUP) { @Override public List<?> getValues(UnknownFieldSet.Field field) { return field.getGroupList(); } }; private static final ImmutableList<Type> TYPES = ImmutableList.copyOf(values()); static ImmutableList<Type> all() { return TYPES; } private final int wireType; Type(int wireType) { this.wireType = wireType; } /** Returns the corresponding values from the given field. */ abstract List<?> getValues(UnknownFieldSet.Field field); /** Returns the {@link WireFormat} constant for this field type. */ final int wireType() { return wireType; } } static UnknownFieldDescriptor create(int fieldNumber, Type type) { return new AutoValue_UnknownFieldDescriptor(fieldNumber, type); } abstract int fieldNumber(); abstract Type type(); static ImmutableList<UnknownFieldDescriptor> descriptors( int fieldNumber, UnknownFieldSet.Field field) {<FILL_FUNCTION_BODY>} }
ImmutableList.Builder<UnknownFieldDescriptor> builder = ImmutableList.builder(); for (Type type : Type.all()) { if (!type.getValues(field).isEmpty()) { builder.add(create(fieldNumber, type)); } } return builder.build();
google_truth
truth/extensions/re2j/src/main/java/com/google/common/truth/extensions/re2j/Re2jSubjects.java
Re2jStringSubject
doesNotMatch
class Re2jStringSubject extends Subject { private static final Subject.Factory<Re2jStringSubject, String> FACTORY = new Subject.Factory<Re2jStringSubject, String>() { @Override public Re2jStringSubject createSubject( FailureMetadata failureMetadata, @Nullable String target) { return new Re2jStringSubject(failureMetadata, target); } }; private final @Nullable String actual; private Re2jStringSubject(FailureMetadata failureMetadata, @Nullable String subject) { super(failureMetadata, subject); this.actual = subject; } @Override protected String actualCustomStringRepresentation() { return quote(checkNotNull(actual)); } /** Fails if the string does not match the given regex. */ public void matches(String regex) { if (!Pattern.matches(regex, checkNotNull(actual))) { failWithActual("expected to match ", regex); } } /** Fails if the string does not match the given regex. */ @GwtIncompatible("com.google.re2j.Pattern") public void matches(Pattern regex) { if (!regex.matcher(checkNotNull(actual)).matches()) { failWithActual("expected to match ", regex); } } /** Fails if the string matches the given regex. */ public void doesNotMatch(String regex) { if (Pattern.matches(regex, checkNotNull(actual))) { failWithActual("expected to fail to match", regex); } } /** Fails if the string matches the given regex. */ @GwtIncompatible("com.google.re2j.Pattern") public void doesNotMatch(Pattern regex) {<FILL_FUNCTION_BODY>} /** Fails if the string does not contain a match on the given regex. */ @GwtIncompatible("com.google.re2j.Pattern") public void containsMatch(Pattern pattern) { if (!pattern.matcher(checkNotNull(actual)).find()) { failWithActual("expected to contain a match for", pattern); } } /** Fails if the string does not contain a match on the given regex. */ public void containsMatch(String regex) { if (!doContainsMatch(checkNotNull(actual), regex)) { failWithActual("expected to contain a match for", regex); } } /** Fails if the string contains a match on the given regex. */ @GwtIncompatible("com.google.re2j.Pattern") public void doesNotContainMatch(Pattern pattern) { if (pattern.matcher(checkNotNull(actual)).find()) { failWithActual("expected not to contain a match for", pattern); } } /** Fails if the string contains a match on the given regex. */ public void doesNotContainMatch(String regex) { if (doContainsMatch(checkNotNull(actual), regex)) { failWithActual("expected not to contain a match for", regex); } } private static String quote(CharSequence toBeWrapped) { return "\"" + toBeWrapped + "\""; } private static boolean doContainsMatch(String subject, String regex) { return Pattern.compile(regex).matcher(subject).find(); } }
if (regex.matcher(checkNotNull(actual)).matches()) { failWithActual("expected to fail to match", regex); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-ant/src/main/java/org/jsonschema2pojo/ant/AntRuleLogger.java
AntRuleLogger
log
class AntRuleLogger extends AbstractRuleLogger { private static final String LEVEL_PREFIX = "["; private static final String LEVEL_SUFFIX = "] "; private static final String DEBUG_LEVEL_PREFIX = LEVEL_PREFIX + "DEBUG" + LEVEL_SUFFIX; private static final String ERROR_LEVEL_PREFIX = LEVEL_PREFIX + "ERROR" + LEVEL_SUFFIX; private static final String INFO_LEVEL_PREFIX = LEVEL_PREFIX + "INFO" + LEVEL_SUFFIX; private static final String TRACE_LEVEL_PREFIX = LEVEL_PREFIX + "TRACE" + LEVEL_SUFFIX; private static final String WARN_LEVEL_PREFIX = LEVEL_PREFIX + "WARN" + LEVEL_SUFFIX; private final Jsonschema2PojoTask task; public AntRuleLogger(Jsonschema2PojoTask jsonschema2PojoTask) { this.task = jsonschema2PojoTask; } @Override public boolean isDebugEnabled() { return true; } @Override public boolean isErrorEnabled() { return true; } @Override public boolean isInfoEnabled() { return true; } @Override public boolean isTraceEnabled() { return true; } @Override public boolean isWarnEnabled() { return true; } protected void doDebug(String msg) { log(msg, null, Project.MSG_DEBUG, DEBUG_LEVEL_PREFIX); } protected void doError(String msg, Throwable e) { log(msg, e, Project.MSG_ERR, ERROR_LEVEL_PREFIX); } protected void doInfo(String msg) { log(msg, null, Project.MSG_INFO, INFO_LEVEL_PREFIX); } protected void doTrace(String msg) { log(msg, null, Project.MSG_VERBOSE, TRACE_LEVEL_PREFIX); } protected void doWarn(String msg, Throwable e) { log(msg, null, Project.MSG_WARN, WARN_LEVEL_PREFIX); } private void log(String msg, Throwable e, int level, String levelPrefix) {<FILL_FUNCTION_BODY>} }
if (task != null && task.getProject() != null) { if(e != null) { task.getProject().log(msg, e, level); } else { task.getProject().log(msg, level); } } else { System.err.println(levelPrefix + msg); if(e != null) { e.printStackTrace(System.err); } }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-cli/src/main/java/org/jsonschema2pojo/cli/ClassConverter.java
ClassConverter
convert
class ClassConverter extends BaseConverter<Class> { /** * Create a new class converter. * * @param optionName * The name of the option that will be using this converter. */ public ClassConverter(String optionName) { super(optionName); } @Override public Class convert(String value) {<FILL_FUNCTION_BODY>} }
if (isBlank(value)) { throw new ParameterException(getErrorString("a blank value", "a class")); } try { return Class.forName(value); } catch (ClassNotFoundException e) { throw new ParameterException(getErrorString(value, "a class")); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-cli/src/main/java/org/jsonschema2pojo/cli/CommandLineLogger.java
CommandLineLogger
printLogLevels
class CommandLineLogger extends AbstractRuleLogger { public static final String DEFAULT_LOG_LEVEL = LogLevel.INFO.value(); private final int logLevel; public CommandLineLogger(String logLevel) { this.logLevel = LogLevel.fromValue(logLevel).levelInt(); } @Override public boolean isDebugEnabled() { return logLevel >= LogLevel.DEBUG.levelInt(); } @Override public boolean isErrorEnabled() { return logLevel >= LogLevel.ERROR.levelInt(); } @Override public boolean isInfoEnabled() { return logLevel >= LogLevel.INFO.levelInt(); } @Override public boolean isTraceEnabled() { return logLevel >= LogLevel.TRACE.levelInt(); } @Override public boolean isWarnEnabled() { return logLevel >= LogLevel.WARN.levelInt(); } public void printLogLevels() {<FILL_FUNCTION_BODY>} @Override protected void doDebug(String msg) { System.out.println(msg); } @Override protected void doError(String msg, Throwable e) { System.err.println(msg); if(e != null) { e.printStackTrace(System.err); } } @Override protected void doInfo(String msg) { System.out.print(msg); } @Override protected void doTrace(String msg) { System.out.print(msg); } @Override protected void doWarn(String msg, Throwable e) { System.err.println(msg); if(e != null) { e.printStackTrace(System.err); } } public enum LogLevel { OFF("off", -2), ERROR("error", -1), WARN("warn", 0), INFO("info", 1), DEBUG("debug", 2), TRACE("trace", 3); private final static Map<String, LogLevel> LEVEL_NAMES = new LinkedHashMap<>(); private final String levelName; private final int levelInt; LogLevel(String value, int levelInt) { this.levelName = value; this.levelInt = levelInt; } @JsonCreator public static LogLevel fromValue(String value) { LogLevel constant = LEVEL_NAMES.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } public static Set<String> getLevelNames() { return LEVEL_NAMES.keySet(); } public int levelInt() { return levelInt; } @Override public String toString() { return this.levelName; } @JsonValue public String value() { return this.levelName; } static { for (LogLevel c : values()) { LEVEL_NAMES.put(c.levelName, c); } } } public static class LogLevelValidator implements IParameterValidator2 { @Override public void validate(String name, String value, ParameterDescription pd) throws ParameterException { Collection<String> availableLogLevels = LogLevel.getLevelNames(); if (!availableLogLevels.contains(value)) { String availableLevelJoined = availableLogLevels.stream().collect(Collectors.joining(", ", "[", "]")); throw new ParameterException("The parameter " + name + " must be one of " + availableLevelJoined); } } @Override public void validate(String name, String value) throws ParameterException { validate(name, value, null); } } }
Set<String> levelNames = LogLevel.getLevelNames(); String levelNamesJoined = levelNames.stream().collect(Collectors.joining(", ")); System.out.println("Available Log Levels: " + levelNamesJoined);
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-cli/src/main/java/org/jsonschema2pojo/cli/Jsonschema2PojoCLI.java
Jsonschema2PojoCLI
main
class Jsonschema2PojoCLI { private Jsonschema2PojoCLI() { } /** * Main method, entry point for the application when invoked via the command * line. Arguments are expected in POSIX format, invoke with --help for * details. * * @param args * Incoming arguments from the command line * @throws FileNotFoundException * if the paths specified on the command line are not found * @throws IOException * if the application is unable to read data from the paths * specified */ public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>} }
Arguments arguments = new Arguments().parse(args); CommandLineLogger logger = new CommandLineLogger(arguments.getLogLevel()); if (arguments.isPrintLogLevels()) { logger.printLogLevels(); arguments.exit(0); } if (arguments.isUseCommonsLang3()) { logger.warn("--commons-lang3 is deprecated. Please remove the argument from your command-line arguments."); } Jsonschema2Pojo.generate(arguments, logger);
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-cli/src/main/java/org/jsonschema2pojo/cli/UrlConverter.java
UrlConverter
convert
class UrlConverter extends BaseConverter<URL> { public UrlConverter(String optionName) { super(optionName); } public URL convert(String value) {<FILL_FUNCTION_BODY>} }
if (isBlank(value)) { throw new ParameterException(getErrorString("a blank value", "a valid URL")); } try { return URLUtil.parseURL(value); } catch (IllegalArgumentException e) { throw new ParameterException(getErrorString(value, "a valid URL")); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/AbstractTypeInfoAwareAnnotator.java
AbstractTypeInfoAwareAnnotator
typeInfo
class AbstractTypeInfoAwareAnnotator extends AbstractAnnotator { public AbstractTypeInfoAwareAnnotator(GenerationConfig generationConfig) { super(generationConfig); } @Override public void typeInfo(JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>} @Override public boolean isPolymorphicDeserializationSupported(JsonNode node) { return getGenerationConfig().isIncludeTypeInfo() || node.has("deserializationClassProperty"); } abstract protected void addJsonTypeInfoAnnotation(JDefinedClass clazz, String propertyName); }
if(getGenerationConfig().isIncludeTypeInfo()) { // Have per-schema JavaTypeInfo configuration override what is defined in generation config; backward comparability if (node.has("deserializationClassProperty")) { String annotationName = node.get("deserializationClassProperty").asText(); addJsonTypeInfoAnnotation(clazz, annotationName); } else { addJsonTypeInfoAnnotation(clazz, "@class"); } } else { // per-schema JsonTypeInfo configuration if (node.has("deserializationClassProperty")) { String annotationName = node.get("deserializationClassProperty").asText(); addJsonTypeInfoAnnotation(clazz, annotationName); } }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/AnnotatorFactory.java
AnnotatorFactory
getAnnotator
class AnnotatorFactory { private final GenerationConfig generationConfig; public AnnotatorFactory(GenerationConfig generationConfig) { this.generationConfig = generationConfig; } /** * Create a new {@link Annotator} that can create annotations according to * the given style. * * @param style * the annotation style that dictates what kind of annotations * are required. * @return an annotator matching to given style */ public Annotator getAnnotator(AnnotationStyle style) { switch (style) { case JACKSON: case JACKSON2: return new Jackson2Annotator(generationConfig); case JSONB1: return new Jsonb1Annotator(generationConfig); case JSONB2: return new Jsonb2Annotator(generationConfig); case GSON: return new GsonAnnotator(generationConfig); case MOSHI1: return new Moshi1Annotator(generationConfig); case NONE: return new NoopAnnotator(); default: throw new IllegalArgumentException("Unrecognised annotation style: " + style); } } /** * Create a new custom {@link Annotator} from the given class. * * @param clazz * A class implementing {@link Annotator}. * @return an instance of the given annotator type */ public Annotator getAnnotator(Class<? extends Annotator> clazz) {<FILL_FUNCTION_BODY>} public CompositeAnnotator getAnnotator( Annotator... annotators ) { return new CompositeAnnotator(annotators); } }
if (!Annotator.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("The class name given as a custom annotator (" + clazz.getName() + ") does not refer to a class that implements " + Annotator.class.getName()); } try { try { Constructor<? extends Annotator> constructor = clazz.getConstructor(GenerationConfig.class); return constructor.newInstance(generationConfig); } catch (NoSuchMethodException e) { return clazz.newInstance(); } } catch (InvocationTargetException | InstantiationException e) { throw new IllegalArgumentException("Failed to create a custom annotator from the given class. An exception was thrown on trying to create a new instance.", e.getCause()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Failed to create a custom annotator from the given class. It appears that we do not have access to this class - is both the class and its no-arg constructor marked public?", e); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/CompositeAnnotator.java
CompositeAnnotator
timeField
class CompositeAnnotator implements Annotator { final Annotator[] annotators; /** * Create a new composite annotator, made up of a given set of child * annotators. * * @param annotators * The annotators that will be called whenever this annotator is * called. The child annotators provided will called in the order * that they appear in this argument list. */ public CompositeAnnotator(Annotator... annotators) { this.annotators = annotators; } @Override public void typeInfo(JDefinedClass clazz, JsonNode node) { for (Annotator annotator : annotators) { annotator.typeInfo(clazz, node); } } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { for (Annotator annotator : annotators) { annotator.propertyOrder(clazz, propertiesNode); } } @Override public void propertyInclusion(JDefinedClass clazz, JsonNode schema) { for (Annotator annotator : annotators) { annotator.propertyInclusion(clazz, schema); } } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { for (Annotator annotator : annotators) { annotator.propertyField(field, clazz, propertyName, propertyNode); } } @Override public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { for (Annotator annotator : annotators) { annotator.propertyGetter(getter, clazz, propertyName); } } @Override public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { for (Annotator annotator : annotators) { annotator.propertySetter(setter, clazz, propertyName); } } @Override public void anyGetter(JMethod getter, JDefinedClass clazz) { for (Annotator annotator : annotators) { annotator.anyGetter(getter, clazz); } } @Override public void anySetter(JMethod setter, JDefinedClass clazz) { for (Annotator annotator : annotators) { annotator.anySetter(setter, clazz); } } @Override public void enumCreatorMethod(JDefinedClass _enum, JMethod creatorMethod) { for (Annotator annotator : annotators) { annotator.enumCreatorMethod(_enum, creatorMethod); } } @Override public void enumValueMethod(JDefinedClass _enum, JMethod valueMethod) { for (Annotator annotator : annotators) { annotator.enumValueMethod(_enum, valueMethod); } } @Override public void enumConstant(JDefinedClass _enum, JEnumConstant constant, String value) { for (Annotator annotator : annotators) { annotator.enumConstant(_enum, constant, value); } } @Override public boolean isAdditionalPropertiesSupported() { for (Annotator annotator : annotators) { if (!annotator.isAdditionalPropertiesSupported()) { return false; } } return true; } @Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { for (Annotator annotator : annotators) { annotator.additionalPropertiesField(field, clazz, propertyName); } } @Override public boolean isPolymorphicDeserializationSupported(JsonNode node) { for (Annotator annotator : annotators) { if (!annotator.isPolymorphicDeserializationSupported(node)) { return false; } } return true; } @Override public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode propertyNode) { for (Annotator annotator : annotators) { annotator.dateTimeField(field, clazz, propertyNode); } } @Override public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode propertyNode) { for (Annotator annotator : annotators) { annotator.dateField(field, clazz, propertyNode); } } @Override public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode propertyNode) {<FILL_FUNCTION_BODY>} }
for (Annotator annotator : annotators) { annotator.timeField(field, clazz, propertyNode); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/ContentResolver.java
ContentResolver
resolveFromClasspath
class ContentResolver { private static final Set<String> CLASSPATH_SCHEMES = new HashSet<>(asList("classpath", "resource", "java")); private final ObjectMapper objectMapper; public ContentResolver() { this(null); } public ContentResolver(JsonFactory jsonFactory) { this.objectMapper = new ObjectMapper(jsonFactory) .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); } /** * Resolve a given URI to read its contents and parse the result as JSON. * <p> * Supported protocols: * <ul> * <li>http/https * <li>file * <li>classpath/resource/java (all synonymous, used to resolve a schema * from the classpath) * </ul> * * @param uri * the URI to read schema content from * @return the JSON tree found at the given URI */ public JsonNode resolve(URI uri) { if (CLASSPATH_SCHEMES.contains(uri.getScheme())) { return resolveFromClasspath(uri); } try { return objectMapper.readTree(uri.toURL()); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Error parsing document: " + uri, e); } catch (IOException e) { throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e); } } private JsonNode resolveFromClasspath(URI uri) {<FILL_FUNCTION_BODY>} }
String path = removeStart(removeStart(uri.toString(), uri.getScheme() + ":"), "/"); InputStream contentAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); if (contentAsStream == null) { throw new IllegalArgumentException("Couldn't read content from the classpath, file not found: " + uri); } try { return objectMapper.readTree(contentAsStream); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Error parsing document: " + uri, e); } catch (IOException e) { throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/FileCodeWriterWithEncoding.java
FileCodeWriterWithEncoding
openSource
class FileCodeWriterWithEncoding extends com.sun.codemodel.writer.FileCodeWriter { public FileCodeWriterWithEncoding(File target, String encoding) throws IOException { super(target, encoding); } @Override public Writer openSource(JPackage pkg, String fileName) throws IOException {<FILL_FUNCTION_BODY>} }
final Writer bw = new OutputStreamWriter(openBinary(pkg, fileName), encoding); return new UnicodeEscapeWriter(bw) { private final CharsetEncoder encoder = Charset.forName(encoding).newEncoder(); @Override protected boolean requireEscaping(int ch) { // control characters if (ch < 0x20 && " \t\r\n".indexOf(ch) == -1) { return true; } // ASCII chars if (ch < 0x80) { return false; } return !encoder.canEncode((char) ch); } };
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/FragmentResolver.java
FragmentResolver
resolve
class FragmentResolver { public JsonNode resolve(JsonNode tree, String path, String refFragmentPathDelimiters) { return resolve(tree, new ArrayList<>(asList(split(path, refFragmentPathDelimiters)))); } private JsonNode resolve(JsonNode tree, List<String> path) {<FILL_FUNCTION_BODY>} }
if (path.isEmpty()) { return tree; } else { String part = path.remove(0); if (tree.isArray()) { try { int index = Integer.parseInt(part); return resolve(tree.get(index), path); } catch (NumberFormatException e) { throw new IllegalArgumentException("Not a valid array index: " + part); } } String decodedPart = JsonPointerUtils.decodeReferenceToken(part); if (tree.has(decodedPart)) { return resolve(tree.get(decodedPart), path); } else { throw new IllegalArgumentException("Path not present: " + decodedPart); } }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jackson2Annotator.java
Jackson2Annotator
dateField
class Jackson2Annotator extends AbstractTypeInfoAwareAnnotator { private final JsonInclude.Include inclusionLevel; public Jackson2Annotator(GenerationConfig generationConfig) { super(generationConfig); switch (generationConfig.getInclusionLevel()) { case ALWAYS: inclusionLevel = JsonInclude.Include.ALWAYS; break; case NON_ABSENT: inclusionLevel = JsonInclude.Include.NON_ABSENT; break; case NON_DEFAULT: inclusionLevel = JsonInclude.Include.NON_DEFAULT; break; case NON_EMPTY: inclusionLevel = JsonInclude.Include.NON_EMPTY; break; case NON_NULL: inclusionLevel = JsonInclude.Include.NON_NULL; break; case USE_DEFAULTS: inclusionLevel = JsonInclude.Include.USE_DEFAULTS; break; default: inclusionLevel = JsonInclude.Include.NON_NULL; break; } } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } } @Override public void propertyInclusion(JDefinedClass clazz, JsonNode schema) { clazz.annotate(JsonInclude.class).param("value", inclusionLevel); } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { field.annotate(JsonProperty.class).param("value", propertyName); if (field.type().erasure().equals(field.type().owner().ref(Set.class))) { field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class); } if (propertyNode.has("javaJsonView")) { field.annotate(JsonView.class).param( "value", field.type().owner().ref(propertyNode.get("javaJsonView").asText())); } if (propertyNode.has("description")) { field.annotate(JsonPropertyDescription.class).param("value", propertyNode.get("description").asText()); } } @Override public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { getter.annotate(JsonProperty.class).param("value", propertyName); } @Override public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { setter.annotate(JsonProperty.class).param("value", propertyName); } @Override public void anyGetter(JMethod getter, JDefinedClass clazz) { getter.annotate(JsonAnyGetter.class); } @Override public void anySetter(JMethod setter, JDefinedClass clazz) { setter.annotate(JsonAnySetter.class); } @Override public void enumCreatorMethod(JDefinedClass _enum, JMethod creatorMethod) { creatorMethod.annotate(JsonCreator.class); } @Override public void enumValueMethod(JDefinedClass _enum, JMethod valueMethod) { valueMethod.annotate(JsonValue.class); } @Override public void enumConstant(JDefinedClass _enum, JEnumConstant constant, String value) { } @Override public boolean isAdditionalPropertiesSupported() { return true; } @Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { field.annotate(JsonIgnore.class); } @Override public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>} @Override public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customTimePattern")) { pattern = node.get("customTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) { pattern = getGenerationConfig().getCustomTimePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_TIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); } } @Override public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String timezone = node.has("customTimezone") ? node.get("customTimezone").asText() : "UTC"; String pattern = null; if (node.has("customDateTimePattern")) { pattern = node.get("customDateTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) { pattern = getGenerationConfig().getCustomDateTimePattern(); } else if (getGenerationConfig().isFormatDateTimes()) { pattern = FormatRule.ISO_8601_DATETIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern).param("timezone", timezone); } } protected void addJsonTypeInfoAnnotation(JDefinedClass jclass, String propertyName) { JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class); jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS); jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY); // When not provided it will use default provided by "use" attribute if (StringUtils.isNotBlank(propertyName)) { jsonTypeInfo.param("property", propertyName); } } }
String pattern = null; if (node.has("customDatePattern")) { pattern = node.get("customDatePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) { pattern = getGenerationConfig().getCustomDatePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_DATE_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/JsonPointerUtils.java
JsonPointerUtils
decodeReferenceToken
class JsonPointerUtils { private static Map<String,String> SUBSTITUTIONS = new LinkedHashMap<String, String>() {{ put("~", "~0"); put("/", "~1"); put("#", "~2"); put(".", "~3"); put("?", "~4"); }}; public static String encodeReferenceToken(final String s) { String encoded = s; for (Map.Entry<String,String> sub : SUBSTITUTIONS.entrySet()) { encoded = encoded.replace(sub.getKey(), sub.getValue()); } return encoded; } public static String decodeReferenceToken(final String s) {<FILL_FUNCTION_BODY>} }
String decoded = s; List<String> reverseOrderedKeys = new ArrayList<String>(SUBSTITUTIONS.keySet()); Collections.reverse(reverseOrderedKeys); for (String key : reverseOrderedKeys) { decoded = decoded.replace(SUBSTITUTIONS.get(key), key); } return decoded;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonb1Annotator.java
Jsonb1Annotator
dateTimeField
class Jsonb1Annotator extends AbstractAnnotator { public Jsonb1Annotator(GenerationConfig generationConfig) { super(generationConfig); } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonbPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { field.annotate(JsonbProperty.class).param("value", propertyName); } @Override public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { getter.annotate(JsonbProperty.class).param("value", propertyName); } @Override public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { setter.annotate(JsonbProperty.class).param("value", propertyName); } @Override public boolean isAdditionalPropertiesSupported() { return true; } @Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { field.annotate(JsonbTransient.class); } @Override public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customDatePattern")) { pattern = node.get("customDatePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) { pattern = getGenerationConfig().getCustomDatePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_DATE_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_DATE_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); } } @Override public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customTimePattern")) { pattern = node.get("customTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) { pattern = getGenerationConfig().getCustomTimePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_TIME_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_TIME_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); } } @Override public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>} }
String pattern = null; if (node.has("customDateTimePattern")) { pattern = node.get("customDateTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) { pattern = getGenerationConfig().getCustomDateTimePattern(); } else if (getGenerationConfig().isFormatDateTimes()) { pattern = FormatRule.ISO_8601_DATETIME_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_DATETIME_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonb2Annotator.java
Jsonb2Annotator
dateField
class Jsonb2Annotator extends AbstractAnnotator { public Jsonb2Annotator(GenerationConfig generationConfig) { super(generationConfig); } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonbPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { field.annotate(JsonbProperty.class).param("value", propertyName); } @Override public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { getter.annotate(JsonbProperty.class).param("value", propertyName); } @Override public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { setter.annotate(JsonbProperty.class).param("value", propertyName); } @Override public boolean isAdditionalPropertiesSupported() { return true; } @Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { field.annotate(JsonbTransient.class); } @Override public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>} @Override public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customTimePattern")) { pattern = node.get("customTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) { pattern = getGenerationConfig().getCustomTimePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_TIME_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_TIME_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); } } @Override public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customDateTimePattern")) { pattern = node.get("customDateTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) { pattern = getGenerationConfig().getCustomDateTimePattern(); } else if (getGenerationConfig().isFormatDateTimes()) { pattern = FormatRule.ISO_8601_DATETIME_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_DATETIME_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); } } }
String pattern = null; if (node.has("customDatePattern")) { pattern = node.get("customDatePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) { pattern = getGenerationConfig().getCustomDatePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_DATE_FORMAT; } if (!field.type().fullName().equals("java.lang.String")) { pattern = pattern != null? pattern : FormatRule.ISO_8601_DATE_FORMAT; field.annotate(JsonbDateFormat.class).param("value", pattern); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonschema2Pojo.java
Jsonschema2Pojo
generate
class Jsonschema2Pojo { /** * Reads the contents of the given source and initiates schema generation. * * @param config * the configuration options (including source and target paths, * and other behavioural options) that will control code * generation * @param logger * a logger appropriate to the current context, usually a wrapper around the build platform logger * @throws FileNotFoundException * if the source path is not found * @throws IOException * if the application is unable to read data from the source */ public static void generate(GenerationConfig config, RuleLogger logger) throws IOException {<FILL_FUNCTION_BODY>} private static ContentResolver createContentResolver(GenerationConfig config) { if (config.getSourceType() == SourceType.YAMLSCHEMA || config.getSourceType() == SourceType.YAML) { return new ContentResolver(new YAMLFactory()); } else { return new ContentResolver(); } } private static SchemaGenerator createSchemaGenerator(GenerationConfig config) { if (config.getSourceType() == SourceType.YAMLSCHEMA || config.getSourceType() == SourceType.YAML) { return new SchemaGenerator(new YAMLFactory()); } else { return new SchemaGenerator(); } } private static RuleFactory createRuleFactory(GenerationConfig config) { Class<? extends RuleFactory> clazz = config.getCustomRuleFactory(); if (!RuleFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("The class name given as a rule factory (" + clazz.getName() + ") does not refer to a class that implements " + RuleFactory.class.getName()); } try { return clazz.newInstance(); } catch (InstantiationException e) { throw new IllegalArgumentException("Failed to create a rule factory from the given class. An exception was thrown on trying to create a new instance.", e.getCause()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Failed to create a rule factory from the given class. It appears that we do not have access to this class - is both the class and its no-arg constructor marked public?", e); } } private static void generateRecursive(GenerationConfig config, SchemaMapper mapper, JCodeModel codeModel, String packageName, List<File> schemaFiles) throws IOException { Collections.sort(schemaFiles, config.getSourceSortOrder().getComparator()); for (File child : schemaFiles) { if (child.isFile()) { if (config.getSourceType() == SourceType.JSON || config.getSourceType() == SourceType.YAML) { // any cached schemas will have ids that are fragments, relative to the previous document (and shouldn't be reused) mapper.getRuleFactory().getSchemaStore().clearCache(); } mapper.generate(codeModel, getNodeName(child.toURI().toURL(), config), defaultString(packageName), child.toURI().toURL()); } else { generateRecursive(config, mapper, codeModel, childQualifiedName(packageName, child.getName()), Arrays.asList(child.listFiles(config.getFileFilter()))); } } } private static String childQualifiedName(String parentQualifiedName, String childSimpleName) { String safeChildName = childSimpleName.replaceAll(NameHelper.ILLEGAL_CHARACTER_REGEX, "_"); return isEmpty(parentQualifiedName) ? safeChildName : parentQualifiedName + "." + safeChildName; } private static void removeOldOutput(File targetDirectory) { if (targetDirectory.exists()) { for (File f : targetDirectory.listFiles()) { delete(f); } } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") private static void delete(File f) { if (f.isDirectory()) { for (File child : f.listFiles()) { delete(child); } } f.delete(); } private static Annotator getAnnotator(GenerationConfig config) { AnnotatorFactory factory = new AnnotatorFactory(config); return factory.getAnnotator(factory.getAnnotator(config.getAnnotationStyle()), factory.getAnnotator(config.getCustomAnnotator())); } public static String getNodeName(URL file, GenerationConfig config) { return getNodeName(file.toString(), config); } public static String getNodeName(String filePath, GenerationConfig config) { try { String fileName = FilenameUtils.getName(URLDecoder.decode(filePath, StandardCharsets.UTF_8.toString())); String[] extensions = config.getFileExtensions() == null ? new String[] {} : config.getFileExtensions(); boolean extensionRemoved = false; for (int i = 0; i < extensions.length; i++) { String extension = extensions[i]; if (extension.length() == 0) { continue; } if (!extension.startsWith(".")) { extension = "." + extension; } if (fileName.endsWith(extension)) { fileName = removeEnd(fileName, extension); extensionRemoved = true; break; } } if (!extensionRemoved) { fileName = FilenameUtils.getBaseName(fileName); } return fileName; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", filePath), e); } } }
Annotator annotator = getAnnotator(config); RuleFactory ruleFactory = createRuleFactory(config); ruleFactory.setAnnotator(annotator); ruleFactory.setGenerationConfig(config); ruleFactory.setLogger(logger); ruleFactory.setSchemaStore(new SchemaStore(createContentResolver(config), logger)); SchemaMapper mapper = new SchemaMapper(ruleFactory, createSchemaGenerator(config)); JCodeModel codeModel = new JCodeModel(); if (config.isRemoveOldOutput()) { removeOldOutput(config.getTargetDirectory()); } for (Iterator<URL> sources = config.getSource(); sources.hasNext();) { URL source = sources.next(); if (URLUtil.parseProtocol(source.toString()) == URLProtocol.FILE && URLUtil.getFileFromURL(source).isDirectory()) { generateRecursive(config, mapper, codeModel, defaultString(config.getTargetPackage()), Arrays.asList(URLUtil.getFileFromURL(source).listFiles(config.getFileFilter()))); } else { mapper.generate(codeModel, getNodeName(source, config), defaultString(config.getTargetPackage()), source); } } if (config.getTargetDirectory().exists() || config.getTargetDirectory().mkdirs()) { CodeWriter sourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } else { throw new GenerationException("Could not create or access target directory " + config.getTargetDirectory().getAbsolutePath()); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Schema.java
Schema
getGrandParent
class Schema { private final URI id; private final JsonNode content; private final Schema parent; private JType javaType; public Schema(URI id, JsonNode content, Schema parent) { this.id = id; this.content = content; this.parent = parent != null ? parent : this; } public JType getJavaType() { return javaType; } public void setJavaType(JType javaType) { this.javaType = javaType; } public void setJavaTypeIfEmpty(JType javaType) { if (this.getJavaType() == null) { this.setJavaType(javaType); } } public URI getId() { return id; } public JsonNode getContent() { return content; } public Schema getParent() { return parent; } public Schema getGrandParent() {<FILL_FUNCTION_BODY>} public boolean isGenerated() { return javaType != null; } }
if (parent == this) { return this; } else { return this.parent.getGrandParent(); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/SchemaGenerator.java
SchemaGenerator
mergeObjectNodes
class SchemaGenerator { private final ObjectMapper objectMapper; public SchemaGenerator() { this(null); } public SchemaGenerator(JsonFactory jsonFactory) { this.objectMapper = new ObjectMapper(jsonFactory) .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); } public ObjectNode schemaFromExample(URL example) { try { JsonNode content = this.objectMapper.readTree(example); return schemaFromExample(content); } catch (IOException e) { throw new GenerationException("Could not process JSON in source file", e); } } public ObjectNode schemaFromExample(JsonNode example) { if (example.isObject()) { return objectSchema(example); } else if (example.isArray()) { return arraySchema(example); } else { return simpleTypeSchema(example); } } private ObjectNode objectSchema(JsonNode exampleObject) { ObjectNode schema = this.objectMapper.createObjectNode(); schema.put("type", "object"); ObjectNode properties = this.objectMapper.createObjectNode(); for (Iterator<String> iter = exampleObject.fieldNames(); iter.hasNext();) { String property = iter.next(); properties.set(property, schemaFromExample(exampleObject.get(property))); } schema.set("properties", properties); return schema; } private ObjectNode arraySchema(JsonNode exampleArray) { ObjectNode schema = this.objectMapper.createObjectNode(); schema.put("type", "array"); if (exampleArray.size() > 0) { JsonNode exampleItem = exampleArray.get(0).isObject() ? mergeArrayItems(exampleArray) : exampleArray.get(0); schema.set("items", schemaFromExample(exampleItem)); } return schema; } private JsonNode mergeArrayItems(JsonNode exampleArray) { ObjectNode mergedItems = this.objectMapper.createObjectNode(); for (JsonNode item : exampleArray) { if (item.isObject()) { mergeObjectNodes(mergedItems, (ObjectNode) item); } } return mergedItems; } private ObjectNode mergeObjectNodes(ObjectNode targetNode, ObjectNode updateNode) {<FILL_FUNCTION_BODY>} private ObjectNode simpleTypeSchema(JsonNode exampleValue) { try { Object valueAsJavaType = this.objectMapper.treeToValue(exampleValue, Object.class); SerializerProvider serializerProvider = new DefaultSerializerProvider.Impl().createInstance(this.objectMapper.getSerializationConfig(), BeanSerializerFactory.instance); if (valueAsJavaType == null) { SchemaAware valueSerializer = NullSerializer.instance; return (ObjectNode) valueSerializer.getSchema(serializerProvider, null); } else if (valueAsJavaType instanceof Long) { // longs are 'integers' in schema terms SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(Integer.class, null); ObjectNode schema = (ObjectNode) valueSerializer.getSchema(serializerProvider, null); schema.put("minimum", Long.MAX_VALUE); return schema; } else { Class<? extends Object> javaTypeForValue = valueAsJavaType.getClass(); SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(javaTypeForValue, null); return (ObjectNode) valueSerializer.getSchema(serializerProvider, null); } } catch (JsonProcessingException e) { throw new GenerationException("Unable to generate a schema for this json example: " + exampleValue, e); } } }
Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode targetValue = targetNode.get(fieldName); JsonNode updateValue = updateNode.get(fieldName); if (targetValue == null) { // Target node doesn't have this field from update node: just add it targetNode.set(fieldName, updateValue); } else { // Both nodes have the same field: merge the values if (targetValue.isObject() && updateValue.isObject()) { // Both values are objects: recurse targetNode.set(fieldName, mergeObjectNodes((ObjectNode) targetValue, (ObjectNode) updateValue)); } else if (targetValue.isArray() && updateValue.isArray()) { // Both values are arrays: concatenate them to be merged later ((ArrayNode) targetValue).addAll((ArrayNode) updateValue); } else { // Values have different types: use the one from the update node targetNode.set(fieldName, updateValue); } } } return targetNode;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/SchemaMapper.java
SchemaMapper
generate
class SchemaMapper { private static final JsonNodeFactory NODE_FACTORY = JsonNodeFactory.instance; private final RuleFactory ruleFactory; private final SchemaGenerator schemaGenerator; /** * Create a schema mapper with the given {@link RuleFactory}. * * @param ruleFactory * A factory used by this mapper to create Java type generation * rules. * @param schemaGenerator * the generator that this mapper will use if the config dictates * that the input documents are plain json (not json schema) */ public SchemaMapper(RuleFactory ruleFactory, SchemaGenerator schemaGenerator) { this.ruleFactory = ruleFactory; this.schemaGenerator = schemaGenerator; } /** * Create a schema mapper with the default {@link RuleFactory} * implementation. * * @see RuleFactory */ public SchemaMapper() { this(new RuleFactory(), new SchemaGenerator()); } /** * Reads a schema and adds generated types to the given code model. * * @param codeModel * the java code-generation context that should be used to * generated new types * @param className * the name of the parent class the represented by this schema * @param packageName * the target package that should be used for generated types * @param schemaUrl * location of the schema to be used as input * @return The top-most type generated from the given file */ public JType generate(JCodeModel codeModel, String className, String packageName, URL schemaUrl) { JPackage jpackage = codeModel._package(packageName); ObjectNode schemaNode = readSchema(schemaUrl); return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(null, schemaNode, null)); } private ObjectNode readSchema(URL schemaUrl) { switch (ruleFactory.getGenerationConfig().getSourceType()) { case JSONSCHEMA: case YAMLSCHEMA: ObjectNode schemaNode = NODE_FACTORY.objectNode(); schemaNode.put("$ref", schemaUrl.toString()); return schemaNode; case JSON: case YAML: return schemaGenerator.schemaFromExample(schemaUrl); default: throw new IllegalArgumentException("Unrecognised source type: " + ruleFactory.getGenerationConfig().getSourceType()); } } public JType generate(JCodeModel codeModel, String className, String packageName, String json, URI schemaLocation) throws IOException { JPackage jpackage = codeModel._package(packageName); JsonNode schemaNode = objectMapper().readTree(json); return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(schemaLocation, schemaNode, null)); } public JType generate(JCodeModel codeModel, String className, String packageName, String json) throws IOException {<FILL_FUNCTION_BODY>} private ObjectMapper objectMapper() { return new ObjectMapper() .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); } public RuleFactory getRuleFactory() { return ruleFactory; } }
JPackage jpackage = codeModel._package(packageName); JsonNode schemaNode = null; if (ruleFactory.getGenerationConfig().getSourceType() == SourceType.JSON || ruleFactory.getGenerationConfig().getSourceType() == SourceType.YAML) { JsonNode jsonNode = objectMapper().readTree(json); schemaNode = schemaGenerator.schemaFromExample(jsonNode); } else { schemaNode = objectMapper().readTree(json); } return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(null, schemaNode, null));
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/SchemaStore.java
SchemaStore
create
class SchemaStore { protected final Map<URI, Schema> schemas = new HashMap<>(); protected final FragmentResolver fragmentResolver = new FragmentResolver(); protected final ContentResolver contentResolver; protected final RuleLogger logger; public SchemaStore() { this.contentResolver = new ContentResolver(); this.logger = new NoopRuleLogger(); } public SchemaStore(ContentResolver contentResolver, RuleLogger logger) { this.contentResolver = contentResolver; this.logger = logger; } /** * Create or look up a new schema which has the given ID and read the * contents of the given ID as a URL. If a schema with the given ID is * already known, then a reference to the original schema will be returned. * * @param id * the id of the schema being created * @param refFragmentPathDelimiters A string containing any characters * that should act as path delimiters when resolving $ref fragments. * @return a schema object containing the contents of the given path */ public synchronized Schema create(URI id, String refFragmentPathDelimiters) { URI normalizedId = id.normalize(); if (!schemas.containsKey(normalizedId)) { URI baseId = removeFragment(id).normalize(); if (!schemas.containsKey(baseId)) { logger.debug("Reading schema: " + baseId); final JsonNode baseContent = contentResolver.resolve(baseId); schemas.put(baseId, new Schema(baseId, baseContent, null)); } final Schema baseSchema = schemas.get(baseId); if (normalizedId.toString().contains("#")) { JsonNode childContent = fragmentResolver.resolve(baseSchema.getContent(), '#' + id.getFragment(), refFragmentPathDelimiters); schemas.put(normalizedId, new Schema(normalizedId, childContent, baseSchema)); } } return schemas.get(normalizedId); } protected URI removeFragment(URI id) { return URI.create(substringBefore(id.toString(), "#")); } /** * Create or look up a new schema using the given schema as a parent and the * path as a relative reference. If a schema with the given parent and * relative path is already known, then a reference to the original schema * will be returned. * * @param parent * the schema which is the parent of the schema to be created. * @param path * the relative path of this schema (will be used to create a * complete URI by resolving this path against the parent * schema's id) * @param refFragmentPathDelimiters A string containing any characters * that should act as path delimiters when resolving $ref fragments. * @return a schema object containing the contents of the given path */ @SuppressWarnings("PMD.UselessParentheses") public Schema create(Schema parent, String path, String refFragmentPathDelimiters) {<FILL_FUNCTION_BODY>} protected boolean selfReferenceWithoutParentFile(Schema parent, String path) { return parent != null && (parent.getId() == null || parent.getId().toString().startsWith("#/")) && path.startsWith("#"); } public synchronized void clearCache() { schemas.clear(); } }
if (!path.equals("#")) { // if path is an empty string then resolving it below results in jumping up a level. e.g. "/path/to/file.json" becomes "/path/to" path = stripEnd(path, "#?&/"); } // encode the fragment for any funny characters if (path.contains("#")) { String pathExcludingFragment = substringBefore(path, "#"); String fragment = substringAfter(path, "#"); URI fragmentURI; try { fragmentURI = new URI(null, null, fragment); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid fragment: " + fragment + " in path: " + path); } path = pathExcludingFragment + "#" + fragmentURI.getRawFragment(); } URI id = (parent == null || parent.getId() == null) ? URI.create(path) : parent.getId().resolve(path); String stringId = id.toString(); if (stringId.endsWith("#")) { try { id = new URI(stripEnd(stringId, "#")); } catch (URISyntaxException e) { throw new IllegalArgumentException("Bad path: " + stringId); } } if (selfReferenceWithoutParentFile(parent, path) || substringBefore(stringId, "#").isEmpty()) { JsonNode parentContent = parent.getGrandParent().getContent(); if (schemas.containsKey(id)) { return schemas.get(id); } else { Schema schema = new Schema(id, fragmentResolver.resolve(parentContent, path, refFragmentPathDelimiters), parent.getGrandParent()); schemas.put(id, schema); return schema; } } return create(id, refFragmentPathDelimiters);
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/model/EnumDefinition.java
EnumDefinition
size
class EnumDefinition { private final JType backingType; private final ArrayList<EnumValueDefinition> enumValues; private final String nodeName; private final JsonNode enumNode; private final EnumDefinitionExtensionType type; public EnumDefinition(String nodeName, JsonNode enumNode, JType backingType, ArrayList<EnumValueDefinition> enumValues, EnumDefinitionExtensionType type) { this.nodeName = nodeName; this.enumNode = enumNode; this.backingType = backingType; this.enumValues = enumValues; this.type = type; } public EnumDefinition(EnumDefinition enumDefinition) { this(enumDefinition, enumDefinition.enumValues); } public EnumDefinition(EnumDefinition enumDefinition, ArrayList<EnumValueDefinition> enumValueDefinitions) { this(enumDefinition.nodeName, enumDefinition.enumNode, enumDefinition.backingType, enumValueDefinitions, enumDefinition.type); } public JType getBackingType() { return backingType; } public JsonNode getEnumNode() { return enumNode; } public String getNodeName() { return nodeName; } public EnumDefinitionExtensionType getType() { return type; } public int size() {<FILL_FUNCTION_BODY>} public Collection<EnumValueDefinition> values() { if (enumValues != null) { return Collections.unmodifiableCollection(enumValues); } else { return Collections.emptyList(); } } }
if (enumValues != null) { return enumValues.size(); } else { return 0; }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/ArrayRule.java
ArrayRule
apply
class ArrayRule implements Rule<JPackage, JClass> { private final RuleFactory ruleFactory; protected ArrayRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } /** * <p>Applies this schema rule to take the required code generation steps.</p> * * <p>When constructs of type "array" appear in the schema, these are mapped to * Java collections in the generated POJO. If the array is marked as having * "uniqueItems" then the resulting Java type is {@link Set}, if not, then * the resulting Java type is {@link List}. The schema given by "items" will * decide the generic type of the collection.</p> * * <p>If the "items" property requires newly generated types, then the type * name will be the singular version of the nodeName (unless overridden by * the javaType property) e.g. * <pre> * "fooBars" : {"type":"array", "uniqueItems":"true", "items":{type:"object"}} * ==&gt; * {@code Set<FooBar> getFooBars(); } * </pre> * * @param nodeName * the name of the property which has type "array" * @param node * the schema "type" node * @param parent * the parent node * @param jpackage * the package into which newly generated types should be added * @return the Java type associated with this array rule, either {@link Set} * or {@link List}, narrowed by the "items" type */ @Override public JClass apply(String nodeName, JsonNode node, JsonNode parent, JPackage jpackage, Schema schema) {<FILL_FUNCTION_BODY>} private String makeSingular(String nodeName) { return Inflector.getInstance().singularize(nodeName); } }
boolean uniqueItems = node.has("uniqueItems") && node.get("uniqueItems").asBoolean(); boolean rootSchemaIsArray = !schema.isGenerated(); JType itemType; if (node.has("items")) { String pathToItems; if (schema.getId() == null || schema.getId().getFragment() == null) { pathToItems = "#/items"; } else { pathToItems = "#" + schema.getId().getFragment() + "/items"; } Schema itemsSchema = ruleFactory.getSchemaStore().create(schema, pathToItems, ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters()); if (itemsSchema.isGenerated()) { itemType = itemsSchema.getJavaType(); } else { itemType = ruleFactory.getSchemaRule().apply(makeSingular(nodeName), node.get("items"), node, jpackage, itemsSchema); itemsSchema.setJavaTypeIfEmpty(itemType); } } else { itemType = jpackage.owner().ref(Object.class); } JClass arrayType; if (uniqueItems) { arrayType = jpackage.owner().ref(Set.class).narrow(itemType); } else { arrayType = jpackage.owner().ref(List.class).narrow(itemType); } if (rootSchemaIsArray) { schema.setJavaType(arrayType); } return arrayType;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/BuilderRule.java
BuilderRule
generateNoArgsBaseBuilderConstructor
class BuilderRule implements Rule<JDefinedClass, JDefinedClass> { private RuleFactory ruleFactory; private ReflectionHelper reflectionHelper; BuilderRule(RuleFactory ruleFactory, ReflectionHelper reflectionHelper) { this.ruleFactory = ruleFactory; this.reflectionHelper = reflectionHelper; } @Override public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass instanceClass, Schema currentSchema) { // Create the inner class for the builder JDefinedClass concreteBuilderClass; JDefinedClass builderClass; try { String concreteBuilderClassName = ruleFactory.getNameHelper().getBuilderClassName(instanceClass); String builderClassName = ruleFactory.getNameHelper().getBaseBuilderClassName(instanceClass); builderClass = instanceClass._class(JMod.ABSTRACT + JMod.PUBLIC + JMod.STATIC, builderClassName); concreteBuilderClass = instanceClass._class(JMod.PUBLIC + JMod.STATIC, concreteBuilderClassName); concreteBuilderClass._extends(builderClass.narrow(instanceClass)); } catch (JClassAlreadyExistsException e) { return e.getExistingClass(); } // Determine which base builder (if any) this builder should inherit from JClass parentBuilderClass = null; JClass parentClass = instanceClass._extends(); if (!(parentClass.isPrimitive() || reflectionHelper.isFinal(parentClass) || Objects.equals(parentClass.fullName(), "java.lang.Object"))) { parentBuilderClass = reflectionHelper.getBaseBuilderClass(parentClass); } // Determine the generic type name and that the builder will create instances of String builderTypeParameterName = ruleFactory.getNameHelper().getBuilderTypeParameterName(instanceClass); JTypeVar instanceType = builderClass.generify(builderTypeParameterName, instanceClass); // For new builders we need to create an instance variable and 'build' method // for inheriting builders we'll receive these from the superType if (parentBuilderClass == null) { // Create the instance variable JFieldVar instanceField = builderClass.field(JMod.PROTECTED, instanceType, "instance"); // Create the actual "build" method JMethod buildMethod = builderClass.method(JMod.PUBLIC, instanceType, "build"); JBlock body = buildMethod.body(); JVar result = body.decl(instanceType, "result"); body.assign(result, JExpr._this().ref(instanceField)); body.assign(JExpr._this().ref(instanceField), JExpr._null()); body._return(result); // Create the noargs builder constructors generateNoArgsBuilderConstructors(instanceClass, builderClass, concreteBuilderClass); } else { // Declare the inheritance builderClass._extends(parentBuilderClass.narrow(parentBuilderClass.owner().ref(builderTypeParameterName))); JMethod buildMethod = builderClass.method(JMod.PUBLIC, instanceType, "build"); buildMethod.annotate(Override.class); JBlock body = buildMethod.body(); body._return(JExpr._super().invoke("build")); // Create the noargs builder constructors generateNoArgsBuilderConstructors(instanceClass, builderClass, concreteBuilderClass); } JMethod builderMethod = instanceClass.method(JMod.PUBLIC + JMod.STATIC, builderClass, "builder"); JBlock builderBody = builderMethod.body(); builderBody._return(JExpr._new(concreteBuilderClass)); return builderClass; } private void generateNoArgsBuilderConstructors(JDefinedClass instanceClass, JDefinedClass baseBuilderClass, JDefinedClass builderClass) { generateNoArgsBaseBuilderConstructor(instanceClass, baseBuilderClass, builderClass); generateNoArgsBuilderConstructor(instanceClass, baseBuilderClass, builderClass); } private void generateNoArgsBuilderConstructor(JDefinedClass instanceClass, JDefinedClass baseBuilderClass, JDefinedClass builderClass) { // Add the constructor to builder. JMethod noArgsConstructor = builderClass.constructor(JMod.PUBLIC); JBlock constructorBlock = noArgsConstructor.body(); // Determine if we need to invoke the super() method for our parent builder if (!(baseBuilderClass.isPrimitive() || reflectionHelper.isFinal(baseBuilderClass) || Objects.equals(baseBuilderClass.fullName(), "java.lang.Object"))) { constructorBlock.invoke("super"); } } private void generateNoArgsBaseBuilderConstructor(JDefinedClass instanceClass, JDefinedClass builderClass, JDefinedClass concreteBuilderClass) {<FILL_FUNCTION_BODY>} }
JMethod noArgsConstructor = builderClass.constructor(JMod.PUBLIC); JAnnotationUse warningSuppression = noArgsConstructor.annotate(SuppressWarnings.class); warningSuppression.param("value", "unchecked"); JBlock constructorBlock = noArgsConstructor.body(); JFieldVar instanceField = reflectionHelper.searchClassAndSuperClassesForField("instance", builderClass); // Determine if we need to invoke the super() method for our parent builder JClass parentClass = builderClass._extends(); if (!(parentClass.isPrimitive() || reflectionHelper.isFinal(parentClass) || Objects.equals(parentClass.fullName(), "java.lang.Object"))) { constructorBlock.invoke("super"); } // Only initialize the instance if the object being constructed is actually this class // if it's a subtype then ignore the instance initialization since the subclass will initialize it constructorBlock.directStatement("// Skip initialization when called from subclass"); JInvocation comparison = JExpr._this().invoke("getClass").invoke("equals").arg(JExpr.dotclass(concreteBuilderClass)); JConditional ifNotSubclass = constructorBlock._if(comparison); ifNotSubclass._then().assign(JExpr._this().ref(instanceField), JExpr.cast(instanceField.type(), JExpr._new(instanceClass)));
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/CommentRule.java
CommentRule
apply
class CommentRule implements Rule<JDocCommentable, JDocComment> { protected CommentRule() { } /** * Applies this schema rule to take the required code generation steps. * <p> * When a $comment node is found and applied with this rule, the value of * the $comment is added as a method and field level JavaDoc comment. * * @param nodeName * the name of the object to which this description applies * @param node * the "$comment" schema node * @param parent * the parent node * @param generatableType * comment-able code generation construct, usually a java class, * which should have this description applied * @return the JavaDoc comment created to contain the description */ @Override public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {<FILL_FUNCTION_BODY>} }
JDocComment javadoc = generatableType.javadoc(); String descriptionText = node.asText(); if(StringUtils.isNotBlank(descriptionText)) { String[] lines = node.asText().split("/\r?\n/"); for(String line : lines) { javadoc.append(line); } } return javadoc;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/DescriptionRule.java
DescriptionRule
apply
class DescriptionRule implements Rule<JDocCommentable, JDocComment> { protected DescriptionRule() { } /** * Applies this schema rule to take the required code generation steps. * <p> * When a description node is found and applied with this rule, the value of * the description is added as a class level JavaDoc comment. * * @param nodeName * the name of the object to which this description applies * @param node * the "description" schema node * @param parent * the parent node * @param generatableType * comment-able code generation construct, usually a java class, * which should have this description applied * @return the JavaDoc comment created to contain the description */ @Override public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {<FILL_FUNCTION_BODY>} }
JDocComment javadoc = generatableType.javadoc(); String descriptionText = node.asText(); if(StringUtils.isNotBlank(descriptionText)) { String[] lines = node.asText().split("/\r?\n/"); for(String line : lines) { javadoc.append(line); } } return javadoc;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/DigitsRule.java
DigitsRule
apply
class DigitsRule implements Rule<JFieldVar, JFieldVar> { private final RuleFactory ruleFactory; protected DigitsRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } @Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {<FILL_FUNCTION_BODY>} private boolean isApplicableType(JFieldVar field) { try { Class<?> fieldClass = Class.forName(field.type().boxify().fullName()); // Support Strings and most number types except Double and Float, per docs on Digits annotations return String.class.isAssignableFrom(fieldClass) || (Number.class.isAssignableFrom(fieldClass) && !Float.class.isAssignableFrom(fieldClass) && !Double.class.isAssignableFrom(fieldClass)); } catch (ClassNotFoundException ignore) { return false; } } }
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && node.has("integerDigits") && node.has("fractionalDigits") && isApplicableType(field)) { final Class<? extends Annotation> digitsClass = ruleFactory.getGenerationConfig().isUseJakartaValidation() ? Digits.class : javax.validation.constraints.Digits.class; JAnnotationUse annotation = field.annotate(digitsClass); annotation.param("integer", node.get("integerDigits").asInt()); annotation.param("fraction", node.get("fractionalDigits").asInt()); } return field;
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/FormatRule.java
FormatRule
apply
class FormatRule implements Rule<JType, JType> { public static String ISO_8601_DATE_FORMAT = "yyyy-MM-dd"; public static String ISO_8601_TIME_FORMAT = "HH:mm:ss.SSS"; public static String ISO_8601_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; private final RuleFactory ruleFactory; private final Map<String, Class<?>> formatTypeMapping; protected FormatRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; this.formatTypeMapping = getFormatTypeMapping(ruleFactory.getGenerationConfig()); } /** * Applies this schema rule to take the required code generation steps. * <p> * This rule maps format values to Java types. By default: * <ul> * <li>"format":"date-time" =&gt; {@link java.util.Date} or {@link org.joda.time.DateTime} (if config useJodaDates is set) * <li>"format":"date" =&gt; {@link String} or {@link org.joda.time.LocalDate} (if config useJodaLocalDates is set) * <li>"format":"time" =&gt; {@link String} or {@link org.joda.time.LocalTime} (if config useJodaLocalTimes is set) * <li>"format":"utc-millisec" =&gt; <code>long</code> * <li>"format":"regex" =&gt; {@link java.util.regex.Pattern} * <li>"format":"color" =&gt; {@link String} * <li>"format":"style" =&gt; {@link String} * <li>"format":"phone" =&gt; {@link String} * <li>"format":"uri" =&gt; {@link java.net.URI} * <li>"format":"email" =&gt; {@link String} * <li>"format":"ip-address" =&gt; {@link String} * <li>"format":"ipv6" =&gt; {@link String} * <li>"format":"host-name" =&gt; {@link String} * <li>"format":"uuid" =&gt; {@link java.util.UUID} * <li>other (unrecognised format) =&gt; baseType * </ul> * * @param nodeName * the name of the node to which this format is applied * @param node * the format node * @param parent * the parent node * @param baseType * the type which which is being formatted e.g. for * <code>{ "type" : "string", "format" : "uri" }</code> the * baseType would be java.lang.String * @return the Java type that is appropriate for the format value */ @Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JType baseType, Schema schema) {<FILL_FUNCTION_BODY>} private Class<?> getType(String format) { return formatTypeMapping.getOrDefault(format, null); } private static Map<String, Class<?>> getFormatTypeMapping(GenerationConfig config) { Map<String, Class<?>> mapping = new HashMap<>(14); mapping.put("date-time", getDateTimeType(config)); mapping.put("date", getDateType(config)); mapping.put("time", getTimeType(config)); mapping.put("utc-millisec", Long.class); mapping.put("regex", Pattern.class); mapping.put("color", String.class); mapping.put("style", String.class); mapping.put("phone", String.class); mapping.put("uri", URI.class); mapping.put("email", String.class); mapping.put("ip-address", String.class); mapping.put("ipv6", String.class); mapping.put("host-name", String.class); mapping.put("uuid", UUID.class); for (Map.Entry<String, String> override : config.getFormatTypeMapping().entrySet()) { String format = override.getKey(); Class<?> type = tryLoadType(override.getValue(), format); if (type != null) { mapping.put(format, type); } } return mapping; } private static Class<?> getDateTimeType(GenerationConfig config) { Class<?> type = tryLoadType(config.getDateTimeType(), "data-time"); if (type != null) { return type; } return config.isUseJodaDates() ? DateTime.class : Date.class; } private static Class<?> getDateType(GenerationConfig config) { Class<?> type = tryLoadType(config.getDateType(), "data"); if (type != null) { return type; } return config.isUseJodaLocalDates() ? LocalDate.class : String.class; } private static Class<?> getTimeType(GenerationConfig config) { Class<?> type = tryLoadType(config.getTimeType(), "time"); if (type != null) { return type; } return config.isUseJodaLocalTimes() ? LocalTime.class : String.class; } private static Class<?> tryLoadType(String typeName, String format) { if (!isEmpty(typeName)) { try { Class<?> type = ClassUtils.getClass(Thread.currentThread().getContextClassLoader(), typeName); return type; } catch (ClassNotFoundException e) { throw new GenerationException(format("could not load java type %s for %s", typeName, format), e); } } return null; } }
Class<?> type = getType(node.asText()); if (type != null) { JType jtype = baseType.owner()._ref(type); if (ruleFactory.getGenerationConfig().isUsePrimitives()) { jtype = jtype.unboxify(); } return jtype; } else { return baseType; }