All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.terapico.utils.DebugUtil Maven / Gradle / Ivy

package com.terapico.utils;

import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.StdDateFormat;

public class DebugUtil {
    private static ObjectMapper _mapper = null;
    private static final NumberFormat cashFormat = new DecimalFormat("#,##0.00");
    
    public static String dumpAsJson(Object object, boolean pretty) throws Exception {
    	if (object == null) {
    		return null;
    	}
        ObjectMapper mapper = getObjectMapper();
		mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		// StdDateFormat is ISO8601 since jackson 2.9
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mapper.setDateFormat(df);
        String jsonStr = null;
        if (pretty) {
            jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } else {
            jsonStr = mapper.writeValueAsString(object);
        }
//        System.out.println(jsonStr);
        return jsonStr;
    }

    public static ObjectMapper getObjectMapper() {
//        if (_mapper != null) {
//            return _mapper.copy();
//        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        return mapper;
    }
    
    public static Map toMap(Object data, String className) throws IOException {
    	ObjectMapper mapper = getObjectMapper();
    	String jsonStr = mapper.writeValueAsString(data);
    	if (className != null && className.endsWith("Form")) {
    		if (data instanceof Map && ((Map) data).containsKey("form")) {
    			System.out.println("新BaseViewPage对象,跳过包装");
    		}else {
	    		Map mapResult = new HashMap<>();
	    		mapResult.put("form", mapper.readValue(jsonStr, Map.class));
	    		return mapResult;
    		}
    	}
    	return mapper.readValue(jsonStr, Map.class);
    }
    public static void renderHashMap(Map map, Writer out, int level) throws IOException {
    	if (map == null || map.isEmpty()) {
    		out.write( "
(empty map)
" ); return; } String template = "
"; out.write(String.format(template, level)); template = "
"+getIconHtml()+"
"; out.write(String.format(template)); List dispkeys = new ArrayList<>(); dispkeys.addAll(map.keySet()); Collections.sort(dispkeys); for(String key : dispkeys) { // while(it.hasNext()) { // Entry ent = it.next(); // String key = ent.getKey(); Object value = map.get(key); if (value instanceof Map && (key.toLowerCase().endsWith("form") && !key.toLowerCase().endsWith("platform"))) { Map form = (Map) value; Map fields = (Map) form.get("fields"); if (fields != null) { template = "
"; out.write(String.format(template)); template = "
"; out.write(String.format(template)); template = "%s"; out.write(String.format(template, form.get("title"))); List keys = new ArrayList<>(fields.keySet()); Collections.sort(keys); for(String fieldName : keys) { Map fieldValue = (Map) fields.get(fieldName); template = "
(%s)%s"; out.write(String.format(template,fieldValue.get("type"), fieldValue.get("name"))); template = ""; if (fieldValue.get("type").equals("images")) { try { template = ""; out.write(String.format(template, fieldValue.get("type"), fieldValue.get("name"), fieldValue.get("value")==null?"":dumpAsJson(fieldValue.get("value"),false))); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { out.write(String.format(template, fieldValue.get("type"), fieldValue.get("name"), fieldValue.get("value")==null?"":fieldValue.get("value"))); } Object candidateValues = fieldValue.get("candidateValues"); template = "
"; out.write(String.format(template)); if (candidateValues != null) { template = "
Candidate values:
%s
"; out.write(String.format(template, getObjectMapper().writeValueAsString(candidateValues))); } } List> actionList = (List>) form.get("actionList"); for(Map action: actionList) { template = ""; out.write(String.format(template, action.get("linkToUrl"), action.get("code"), action.get("title"))); } template = "
"; out.write(String.format(template)); continue; } } if (value instanceof Map) { template = "
"; out.write(String.format(template)); if (putArchor(key, out)) { template = "
%s
(%d members)
"; out.write(String.format(template, key, ((Map) value).size())); out.write(""); } else { template = "
%s
(%d members)
"; out.write(String.format(template, key, ((Map) value).size())); } template = "
"+getIconHtml()+"
"; out.write(String.format(template)); renderObject(key, value, out, level+1); template = "
"; out.write(String.format(template)); continue; } if (value instanceof List) { template = "
"; out.write(String.format(template)); template = "
"+getIconHtml()+"
"; out.write(String.format(template)); template="
%s
(%d items)
" ; out.write(String.format(template, key+"[...]", ((List) value).size())); List list = (List) value; for(Object obj : list) { renderObject(key, obj, out, level+1); } template = ""; out.write(String.format(template)); continue; } template = "
"; out.write(String.format(template)); template="
%s
" ; out.write(String.format(template, key)); renderObject(key, value, out, level+1); template = "
"; out.write(String.format(template)); } template = ""; out.write(template); if (level == 1) { template = "
" + "
" +
					"";
			out.write(template);
			try {
				out.write(DebugUtil.dumpAsJson(map, true));
			} catch (Exception e) {
				e.printStackTrace();
			}
			template = "
"; out.write(template); } } private static String getIconHtml() { return ""; } private static boolean putArchor(String key, Writer out) throws IOException { Matcher m = ptnDataIdIndex.matcher(key); if (!m.matches()) { return false; } out.write(""); return true; } private static Pattern ptnDataIdIndex = Pattern.compile("^[a-zA-Z0-9]+(_[A-Z]+\\d+)+$"); private static void renderObject(String key, Object value, Writer out, int level) throws IOException { if (putArchorLink(key, value, out)) { String template = "%s"; out.write(String.format(template, value, value)); return; } String template="
%s
" ; if (isImageData(key, value)) { template = ""; out.write(String.format(template, value)); return; } if (key.equals("linkToUrl") || key.endsWith("LinkToUrl") || key.equals("nextPageUrl")) { template = ""; out.write(String.format(template, value, value)); return; } if (value instanceof Map) { renderHashMap((Map) value, out, level); return; } if (value instanceof List) { List list = (List) value; for(Object obj : list) { renderObject(key, obj, out, level); } return; } if (value instanceof Number && (key.toLowerCase().endsWith("time") || key.toLowerCase().endsWith("date"))) { template = "
%s
"; out.write(String.format(template, DateTimeUtil.formatDate(new Date(((Number)value).longValue()), null))); return; } if (value instanceof Number && (key.toLowerCase().endsWith("price") || key.toLowerCase().endsWith("date"))) { template = "
%s
"; out.write(String.format(template, cashFormat.format(new BigDecimal(value.toString())))); return; } template="
%s
" ; out.write(String.format(template, value)); } public static boolean isImageData(String key, Object value) { if ( key.equals("imageUrl") || key.toLowerCase().endsWith("image") || key.toLowerCase().endsWith("imageurl")) { return true; } if (key.endsWith("Logo")) { return true; } if (key.toLowerCase().endsWith("avatar")){ return true; } return false; } private static boolean putArchorLink(String key, Object value, Writer out) throws IOException { if (!key.equals("id")) { return false; } if (!(value instanceof String)) { return false; } String strVal = (String) value; Matcher m = ptnDataIdIndex.matcher(strVal); if (!m.matches()) { return false; } // out.write("(to: "+value+")"); return true; } public static void dumpFullStackTrace(Throwable t, PrintStream s) { if (s == null) { s = System.out; } s.println(t.getClass().getCanonicalName()+": " + t.getMessage()); if (t.getStackTrace() != null) { for(StackTraceElement st : t.getStackTrace()) { s.println(" at " + st.getClassName()+"." + st.getMethodName()+"("+st.getFileName()+":"+st.getLineNumber()+")"); } } t = t.getCause(); while(t != null) { s.println("Caused by: " + t.getClass().getCanonicalName()+": " + t.getMessage()); if (t.getStackTrace() != null) { for(StackTraceElement st : t.getStackTrace()) { s.println(" at " + st.getClassName()+"." + st.getMethodName()+"("+st.getFileName()+":"+st.getLineNumber()+")"); } } t = t.getCause(); } } public static T fromJson(String json, TypeReference type) throws IOException { if (json == null || json.isEmpty()){ return null; } return getObjectMapper().readValue(json, type); } public static T fromJson(String json, Class type) throws IOException { if (json == null || json.isEmpty()){ return null; } return getObjectMapper().readValue(json, type); } }