package com.chenyang.nse.bussiness.webtools.tools.jdbc;

import cn.hutool.core.codec.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.engine.jdbc.SerializableBlobProxy;

public class BlobAndBase64Util {
   Blob blob;

   public static String getBase64InBlob(Object blobDate) {
      String result = new String();

      try {
         SerializableBlobProxy proxy = (SerializableBlobProxy)Proxy.getInvocationHandler(blobDate);
         Blob realBlob = proxy.getWrappedBlob();
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         byte[] buff = new byte[100];
         int rc = 0;
         InputStream binaryStream = realBlob.getBinaryStream();

         while((rc = binaryStream.read(buff, 0, 100)) > 0) {
            byteArrayOutputStream.write(buff, 0, rc);
         }

         byte[] byteArray = byteArrayOutputStream.toByteArray();
         result = Base64.encode(byteArray);
      } catch (IOException e) {
         e.printStackTrace();
      } catch (SQLException e) {
         e.printStackTrace();
      }

      return result;
   }

   public static String getBase64FromBlob(Object objDate) throws IOException {
      String result = new String();
      Blob blob = (Blob)objDate;

      try {
         byte[] valueArr = null;
         if (null != blob) {
            valueArr = blob.getBytes(1L, (int)blob.length());
         }

         result = Base64.encode(valueArr);
      } catch (SQLException e) {
         e.printStackTrace();
      }

      return result;
   }
}
