content: package cn.hotapk.fastandrutils.utils;
  
  import com.google.gson.Gson;
  import com.google.gson.GsonBuilder;
  import com.google.gson.JsonElement;
  import com.google.gson.JsonParser;
  
  import java.io.ByteArrayInputStream;
  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.UnsupportedEncodingException;
  import java.lang.reflect.Field;
  import java.lang.reflect.Modifier;
  import java.math.BigDecimal;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  
  /**
   * @author laijian
   * @version 2017/9/19
   * @Copyright (C)上午11:37 , www.hotapk.cn
   * 数据转换
   */
  public final class FConvertUtils {
  
      private static final int KB = 1024;
      private static final int MAX_BLOB_LENGTH = 512;
  
      private static final String UNKNOWN_BLOB_LABEL = "{blob}";
  
      private FConvertUtils() {
  
      }
  
  
      /**
       * 将px值转换为dip或dp值，保证尺寸大小不变
       *
       * @param pxValue （DisplayMetrics类中属性density）
       * @return
       */
      public static int px2dip(float pxValue) {
          final float scale = FUtils.getAppContext().getResources().getDisplayMetrics().density;
          return (int) (pxValue / scale + 0.5f);
      }
  
      /**
       * 将dip或dp值转换为px值，保证尺寸大小不变
       *
       * @param dipValue （DisplayMetrics类中属性density）
       * @return
       */
      public static int dip2px(float dipValue) {
          final float scale = FUtils.getAppContext().getResources().getDisplayMetrics().density;
          return (int) (dipValue * scale + 0.5f);
      }
  
      /**
       * 将px值转换为sp值，保证文字大小不变
       *
       * @param pxValue （DisplayMetrics类中属性scaledDensity）
       * @return
       */
      public static int px2sp(float pxValue) {
          final float fontScale = FUtils.getAppContext().getResources().getDisplayMetrics().scaledDensity;
          return (int) (pxValue / fontScale + 0.5f);
      }
  
      /**
       * 将sp值转换为px值，保证文字大小不变
       *
       * @param spValue （DisplayMetrics类中属性scaledDensity）
       * @return
       */
      public static int sp2px(float spValue) {
          final float fontScale = FUtils.getAppContext().getResources().getDisplayMetrics().scaledDensity;
          return (int) (spValue * fontScale + 0.5f);
      }
  
  
      /**
       * inputStream转outputStream
       *
       * @param is 输入流
       * @return outputStream子类
       */
      public static ByteArrayOutputStream input2OutputStream(final InputStream is) {
          if (is == null) return null;
          try {
              ByteArrayOutputStream os = new ByteArrayOutputStream();
              byte[] b = new byte[KB];
              int len;
              while ((len = is.read(b, 0, KB)) != -1) {
                  os.write(b, 0, len);
              }
              return os;
          } catch (IOException e) {
              e.printStackTrace();
              return null;
          } finally {
              FCloseUtils.closeIO(is);
          }
      }
  
      /**
       * inputStream转byteArr
       *
       * @param is 输入流
       * @return 字节数组
       */
      public static byte[] inputStream2Bytes(final InputStream is) {
          if (is == null) return null;
          return input2OutputStream(is).toByteArray();
      }
  
      /**
       * byteArr转inputStream
       *
       * @param bytes 字节数组
       * @return 输入流
       */
      public static InputStream bytes2InputStream(final byte[] bytes) {
          if (bytes == null || bytes.length <= 0) return null;
          return new ByteArrayInputStream(bytes);
      }
  
      /**
       * outputStream转byteArr
       *
       * @param out 输出流
       * @return 字节数组
       */
      public static byte[] outputStream2Bytes(final OutputStream out) {
          if (out == null) return null;
          return ((ByteArrayOutputStream) out).toByteArray();
      }
  
      /**
       * byteArr转outputStream
       *
       * @param bytes 字节数组
       * @return 字节数组
       */
      public static OutputStream bytes2OutputStream(final byte[] bytes) {
          if (bytes == null || bytes.length <= 0) return null;
          ByteArrayOutputStream os = null;
          try {
              os = new ByteArrayOutputStream();
              os.write(bytes);
              return os;
          } catch (IOException e) {
              e.printStackTrace();
              return null;
          } finally {
              FCloseUtils.closeIO(os);
          }
      }
  
      /**
       * inputStream转string按编码
       *
       * @param is          输入流
       * @param charsetName 编码格式
       * @return 字符串
       */
      public static String inputStream2String(final InputStream is, final String charsetName) {
          if (is == null || isSpace(charsetName)) return null;
          try {
              return new String(inputStream2Bytes(is), charsetName);
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      /**
       * string转inputStream按编码
       *
       * @param string      字符串
       * @param charsetName 编码格式
       * @return 输入流
       */
      public static InputStream string2InputStream(final String string, final String charsetName) {
          if (string == null || isSpace(charsetName)) return null;
          try {
              return new ByteArrayInputStream(string.getBytes(charsetName));
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      /**
       * outputStream转string按编码
       *
       * @param out         输出流
       * @param charsetName 编码格式
       * @return 字符串
       */
      public static String outputStream2String(final OutputStream out, final String charsetName) {
          if (out == null || isSpace(charsetName)) return null;
          try {
              return new String(outputStream2Bytes(out), charsetName);
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      /**
       * string转outputStream按编码
       *
       * @param string      字符串
       * @param charsetName 编码格式
       * @return 输入流
       */
      public static OutputStream string2OutputStream(final String string, final String charsetName) {
          if (string == null || isSpace(charsetName)) return null;
          try {
              return bytes2OutputStream(string.getBytes(charsetName));
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      /**
       * 对象转map
       *
       * @param obj
       * @return
       */
      public static Map<String, Object> obj2Map(Object obj) throws Exception {
          if (obj == null) {
              return null;
          }
          //获取关联的所有类，本类以及所有父类
          boolean ret = true;
          Class oo = obj.getClass();
          List<Class> clazzs = new ArrayList<Class>();
          while (ret) {
              clazzs.add(oo);
              oo = oo.getSuperclass();
              if (oo == null || oo == Object.class) break;
          }
  
          Map<String, Object> map = new HashMap<String, Object>();
  
          for (int i = 0; i < clazzs.size(); i++) {
              Field[] declaredFields = clazzs.get(i).getDeclaredFields();
              for (Field field : declaredFields) {
                  int mod = field.getModifiers();
                  //过滤 static 和 final 类型
                  if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                      continue;
                  }
                  field.setAccessible(true);
                  map.put(field.getName(), field.get(obj));
              }
          }
  
          return map;
      }
  
      /**
       * map 转对象
       *
       * @param map
       * @param beanClass
       * @return
       * @throws Exception
       */
      public static Object map2Obj(Map<String, String> map, Class<?> beanClass) throws Exception {
          if (map == null || map.size() <= 0)
              return null;
  
          Object obj = beanClass.newInstance();
          //获取关联的所有类，本类以及所有父类
          boolean ret = true;
          Class oo = obj.getClass();
          List<Class> clazzs = new ArrayList<Class>();
          while (ret) {
              clazzs.add(oo);
              oo = oo.getSuperclass();
              if (oo == null || oo == Object.class) break;
          }
  
          for (int i = 0; i < clazzs.size(); i++) {
              Field[] fields = clazzs.get(i).getDeclaredFields();
              for (Field field : fields) {
                  int mod = field.getModifiers();
                  if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                      continue;
                  }
                  //由字符串转换回对象对应的类型
                  if (field != null) {
                      field.setAccessible(true);
                      field.set(obj, map.get(field.getName()));
                  }
              }
          }
          return obj;
      }
  
      /**
       * map转成字符串
       *
       * @param map
       * @param filterls 过滤一些值
       * @return
       */
      public static String map2String(Map map, List<String> filterls) {
          java.util.Map.Entry entry;
          StringBuffer sb = new StringBuffer();
          for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
              entry = (java.util.Map.Entry) iterator.next();
              boolean hasFilter = false;
              if (filterls != null) {
                  for (int i = 0; i < filterls.size(); i++) {
                      if (entry.getKey().equals(filterls.get(i))) {
                          filterls.remove(i);
                          hasFilter = true;
                          break;
                      }
                  }
                  if (hasFilter) {
                      hasFilter = false;
                      continue;
                  }
              }
              sb.append(entry.getKey().toString()).append("=").append(
                      null == entry.getValue() ? "" :
                              entry.getValue().toString() + "\n").append(iterator.hasNext() ? "\n" : "");
          }
          return sb.toString();
      }
  
      /**
       * 二进制单位转换
       *
       * @param size
       * @return
       */
      public static String binaryFormatSize(double size) {
          double kiloByte = size / 1024;
          if (kiloByte < 1) {
              return size + "Byte";
          }
  
          double megaByte = kiloByte / 1024;
          if (megaByte < 1) {
              BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
              return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                      .toPlainString() + "KB";
          }
  
          double gigaByte = megaByte / 1024;
          if (gigaByte < 1) {
              BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
              return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                      .toPlainString() + "MB";
          }
  
          double teraBytes = gigaByte / 1024;
          if (teraBytes < 1) {
              BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
              return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                      .toPlainString() + "GB";
          }
          BigDecimal result4 = new BigDecimal(teraBytes);
          return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                  + "TB";
      }
  
      /**
       * 判断字符串是否为null或全为空白字符
       *
       * @param s 待校验字符串
       * @return {@code true}: null或全空白字符<br> {@code false}: 不为null且不全空白字符
       */
      private static boolean isSpace(final String s) {
          if (s == null) return true;
          for (int i = 0, len = s.length(); i < len; ++i) {
              if (!Character.isWhitespace(s.charAt(i))) {
                  return false;
              }
          }
          return true;
      }
  
      /**
       * json格式化
       *
       * @param uglyJSONString
       * @return
       */
      public static String jsonFormatter(String uglyJSONString) {
          Gson gson = new GsonBuilder().setPrettyPrinting().create();
          JsonParser jp = new JsonParser();
          JsonElement je = jp.parse(uglyJSONString);
          String prettyJsonString = gson.toJson(je);
          return prettyJsonString;
      }
  
      /**
       * blob转字符串
       *
       * @param blob
       * @return
       */
      public static String blobToString(byte[] blob) {
          if (blob.length <= MAX_BLOB_LENGTH) {
              if (fastIsAscii(blob)) {
                  try {
                      return new String(blob, "US-ASCII");
                  } catch (UnsupportedEncodingException ignored) {
  
                  }
              }
          }
          return UNKNOWN_BLOB_LABEL;
      }
  
      public static boolean fastIsAscii(byte[] blob) {
          for (byte b : blob) {
              if ((b & ~0x7f) != 0) {
                  return false;
              }
          }
          return true;
      }
  
      /**
       * outputStream转inputStream
       *
       * @param out 输出流
       * @return inputStream子类
       */
      public ByteArrayInputStream output2InputStream(final OutputStream out) {
          if (out == null) return null;
          return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
      }
  }
  