package com.arsdigita.content;

// $Id: Util-oracle.sqlj,v 1.1 2001/04/05 18:23:38 donb Exp $

import java.sql.*;
import java.util.*;
import oracle.sql.*;
import java.io.*;

public class Util {

  public static void stringToBlob(String s, oracle.sql.BLOB blob, int size) 
    throws SQLException {

    if (s == null) return;

    byte[] inBuffer = s.getBytes();

    if (size < inBuffer.length) size = inBuffer.length;

    byte[] buffer = new byte[size];
    
    System.arraycopy(inBuffer, 0, buffer, 0, inBuffer.length);

    blob.putBytes(1, buffer);
  }

  public static void stringToBlob(String s, oracle.sql.BLOB blob) 
    throws SQLException {
  
    if (s == null) return;
 
    blob.putBytes(1, s.getBytes());
  }

  public static String blobToString(oracle.sql.BLOB blob) 
    throws SQLException {

    if (blob == null || blob.length() == 0) return "";

    byte[] buffer = new byte[(int) blob.length()];

    blob.getBytes(1, (int) blob.length(), buffer);

    String s = new String(buffer);

    return s;
  }

  public static void blobToFile(String path, oracle.sql.BLOB blob) 
    throws SQLException {
  
    try {
 
      File aFile = new File(path);
      FileOutputStream aFileOutputStream = new FileOutputStream(aFile);
      long blobLength =  blob.length();
    
      aFile.mkdirs(); 

      int chunkSize = blob.getChunkSize();
      byte[] buffer = new byte[chunkSize];
      for(long pos = 1; pos < blobLength; pos += chunkSize) {
        chunkSize = blob.getBytes(pos, chunkSize, buffer);
        aFileOutputStream.write(buffer, 0, chunkSize);
      }
      aFileOutputStream.close();
    } catch (IOException e) {
      System.err.println("Error in writing " + path + ": " + e);
    }
  }

  public static void clobToBlob(oracle.sql.CLOB clob, oracle.sql.BLOB blob)
    throws SQLException, IOException {

    if (clob == null) {
      throw new SQLException("Received null value for clob argument.");
    }

    if (blob == null) {
      throw new SQLException("Received null value for blob argument.");
    }

    OutputStream outstream = blob.getBinaryOutputStream();

    // Get an input stream for the clob
    Reader instream = clob.getCharacterStream();

    int size = 4096;
    char[] buffer = new char[size];
    int length = -1;

    while ((length = instream.read(buffer)) != -1)
      outstream.write((new String(buffer)).getBytes(), 0, length);
    instream.close();
    outstream.close();
  }

  // Write a BLOB to a CLOB, assuming the BLOB contains UTF-8 string

  public static void blobToClob(oracle.sql.BLOB blob, oracle.sql.CLOB clob)
    throws SQLException, IOException {

    String s = blobToString(blob);

    // Get an output stream for the clob
    Writer outstream = clob.getCharacterOutputStream();

    outstream.write(s);
    outstream.close();
  }
}
