001/* 002 * Copyright 2019 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.cms.search.query; 017 018import java.lang.reflect.Field; 019import java.lang.reflect.Modifier; 020import java.util.ArrayList; 021import java.util.Arrays; 022import java.util.List; 023import java.util.stream.Collectors; 024 025import org.apache.commons.lang3.StringUtils; 026 027final class QueryDebugger 028{ 029 private QueryDebugger() 030 { } 031 032 static final String toDebugString(Query query, int indent) 033 { 034 String toStr; 035 try 036 { 037 toStr = query.getClass().getSimpleName() 038 + "(" 039 + _getFields(query).stream() 040 .filter(QueryDebugger::_showField) 041 .map(f -> _fieldToString(f, query)) 042 .collect(Collectors.joining(",")) 043 + ")"; 044 } 045 catch (Exception e) 046 { 047 toStr = query.toString(); 048 } 049 return StringUtils.repeat(' ', indent) + toStr; 050 } 051 052 private static final List<Field> _getFields(Query query) 053 { 054 List<Field> fields = new ArrayList<>(); 055 for (Class< ? > clazz = query.getClass(); clazz != null; clazz = clazz.getSuperclass()) 056 { 057 fields.addAll(Arrays.asList(clazz.getDeclaredFields())); 058 } 059 return fields; 060 } 061 062 private static final boolean _showField(Field f) 063 { 064 return !Modifier.isStatic(f.getModifiers()); 065 } 066 067 private static final String _fieldToString(Field f, Query query) 068 { 069 try 070 { 071 f.setAccessible(true); 072 Object val = f.get(query); 073 String strVal = val != null && val.getClass().isArray() 074 ? Arrays.toString((Object[]) val) 075 : String.valueOf(val); 076 return f.getName() + ":" + strVal; 077 } 078 catch (Exception e) 079 { 080 return ""; 081 } 082 } 083}