import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.mariadb.jdbc.Driver;

public class BlobTest {

	/**
	 * @param args
	 */
	public static void main( final String[] args ) throws Throwable {
		final Connection con = getConnection();
		createTestData( con );

		final Statement sta = con.createStatement();
		try {
			final ResultSet set = sta.executeQuery( "Select name,archive as text FROM mariadb_test" );
			try {
				while( set.next() ) {
					System.err.print( set.getString( "name" ) + " : " );

					final Blob blob = set.getBlob( "text" );
					if( blob == null )
						System.err.println( "IS NULL" );
					else {
						final ByteArrayOutputStream bout = new ByteArrayOutputStream( (int)blob.length() );
						try {
							final InputStream bin = blob.getBinaryStream();
							try {
								final byte[] buffer = new byte[ 1024 * 4 ];

								for( int read = bin.read( buffer );read != -1;read = bin.read( buffer ) )
									bout.write( buffer,0,read );

								System.err.println( new String( bout.toByteArray(),"UTF-8" ) );
							}
							finally {
								if( bin != null )
									bin.close();
							}

						}
						finally {
							if( bout != null )
								bout.close();
						}

					}
				}
			}
			finally {
				if( set != null )
					set.close();
			}
		}
		finally {
			if( sta != null )
				sta.close();
		}

	}

	static public void createTestData( final Connection con ) throws SQLException {
		final Statement sta = con.createStatement();
		try {
			sta.execute( "DROP TABLE IF EXISTS mariadb_test" );
			sta.execute( "CREATE TABLE mariadb_test ( Name VARCHAR(100) NOT NULL,Archive LONGBLOB, PRIMARY KEY (Name)) Engine=InnoDB DEFAULT CHARSET utf8" );

			final PreparedStatement pre = con.prepareStatement( "INSERT INTO mariadb_test (Name,Archive) VALUES (?,?)" );
			try {
				pre.setString( 1,"Empty String" );
				pre.setBytes( 2,"".getBytes() );
				pre.addBatch();

				pre.setString( 1,"Data Hello" );
				pre.setBytes( 2,"hello".getBytes() );
				pre.addBatch();

				pre.setString( 1,"Empty Data null" );
				pre.setBytes( 2,null );
				pre.addBatch();

				pre.executeBatch();
			}
			finally {
				if( pre != null )
					pre.close();
			}
		}
		finally {
			if( sta != null )
				sta.close();
		}
	}

	static public Connection getConnection() throws SQLException {
		new Driver();

		return DriverManager.getConnection( "jdbc:mariadb://localhost/mariadb_test","root","" );
	}
}
