How to save and read Oracle Blob from java

I wanted to save and load large binary objects (BLOB) from Oralce database and get into array of bytes in Java.

The access to database cound’t be done directly to the table, it uses a stored procedure that insert’s the record and returns then primary key of the table.

After long research, I’m giving back to the community…

I use an object UtilsDB.getDataSource().getConnection(); to get a connection from JNDI … bue the important is you have some way to get the database connection.

Atention: This doesn’t work if you’re using ojdbc14-9.0.2.0.0.jar. I had to change this jar to ojdbc14-10.2.0.3.0.jar, then it worked ok.

So, to save a chunck of bytes (a PDF file, for example) into a Dabatase

public BigDecimal saveBlobIntoDatabase (byte [] ficheiro,
String nomFicheiro,
String nomDirectoria)
throws SQLException, IOException {

Connection oracleConnection = UtilsDB.getDataSource().getConnection();

CallableStatement stmt = oracleConnection.prepareCall(DBResources.F_GRAVA_BLOB_BD);

BLOB blob = BLOB.createTemporary(oracleConnection, false, BLOB.DURATION_SESSION);

OutputStream outputStream = blob.setBinaryStream(0L);
InputStream inputStream = new ByteArrayInputStream(ficheiro);
byte[] buffer = new byte[blob.getBufferSize()];
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, byteread);
}
outputStream.close();
inputStream.close();

BigDecimal numFicheiro = new BigDecimal(0);
stmt.registerOutParameter(1, OracleTypes.NUMBER);
stmt.setBlob(2, blob);
stmt.setString(3, nomFicheiro);
stmt.setString(4, nomDirectoria);
stmt.execute();
numFicheiro = stmt.getBigDecimal(1);
stmt.close();

return numFicheiro;

}

To read (do the reverse):

public byte[] getBlobFromDatabase(BigDecimal numFicheiro) throws BusinessException {

Connection conn = null;
try {

conn = (Connection) UtilsDB.getDataSource().getConnection();

CallableStatement ocs = null;
byte[] content = null;

try {

ocs = conn.prepareCall(DBResources.F_OBTEM_BLOB_BD);

ocs.registerOutParameter(1, OracleTypes.BLOB);
ocs.setBigDecimal(2, numFicheiro );

ocs.executeQuery();

BLOB blob = null;
if (ocs.getObject(1) instanceof BLOB) {
blob = (BLOB) ocs.getObject(1);
}

content = new byte[ (int) blob.length()];
InputStream blobstream = blob.getBinaryStream();
try {
blobstream.read(content , 0 , (int) blob.length());
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
try {
blobstream.close();
} catch (Exception ignored) {}
}
return content;

} catch (SQLException sqlex) {
sqlex.printStackTrace();
throw sqlex;
} finally {
UtilsDB.close(ocs);
}
} catch (Exception daoe) {
throw new BusinessException(daoe.getMessage() , daoe);
} finally {
UtilsDB.close(conn);
}

}

Also read from:

http://stackoverflow.com/questions/862355/overcomplicated-oracle-jdbc-blob-handling

public byte[] getBlobFromDatabase(BigDecimal numFicheiro) throws BusinessException {Connection conn = null;
try {conn = (Connection) UtilsDB.getDataSource().getConnection();

CallableStatement ocs = null;
byte[] content = null;

try {
Logger.getLogger(“pt.mapfre.pdf.dao”).
log(Level.INFO, “{? = call jf_k_merge.f_obtem_blob_BD(“+numFicheiro+”)}”);

ocs = conn.prepareCall(DBResources.F_OBTEM_BLOB_BD);

ocs.registerOutParameter(1, OracleTypes.BLOB);
ocs.setBigDecimal(2, numFicheiro );

ocs.executeQuery();

//                System.out.println(“CLO: ” + ocs.getObject(1));
//                System.out.println(“CLOB CLASS: ” + ocs.getObject(1).getClass());
//                System.out.println(“IMPORTED CLOB CLASS: ” + BLOB.class);

BLOB blob = null;
if (ocs.getObject(1) instanceof BLOB) {
blob = (BLOB) ocs.getObject(1);
}

content = new byte[ (int) blob.length()];
InputStream blobstream = blob.getBinaryStream();
try {
blobstream.read(content , 0 , (int) blob.length());
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
try {
blobstream.close();
} catch (Exception ignored) {}
}

return content;

} catch (SQLException sqlex) {
sqlex.printStackTrace();
throw sqlex;
} finally {
UtilsDB.close(ocs);
}

} catch (Exception daoe) {
Logger.getLogger(“pt.mapfre.pdf.dao”).
log(Level.SEVERE, “Erro na geracao de PDF”, daoe);
throw new BusinessException(daoe.getMessage() , daoe);
} finally {
UtilsDB.close(conn);
}
public byte[] getBlobFromDatabase(BigDecimal numFicheiro) throws BusinessException {

Connection conn = null;
try {

conn = (Connection) UtilsDB.getDataSource().getConnection();

CallableStatement ocs = null;
byte[] content = null;

try {
Logger.getLogger(“pt.mapfre.pdf.dao”).
log(Level.INFO, “{? = call jf_k_merge.f_obtem_blob_BD(“+numFicheiro+”)}”);

ocs = conn.prepareCall(DBResources.F_OBTEM_BLOB_BD);

ocs.registerOutParameter(1, OracleTypes.BLOB);
ocs.setBigDecimal(2, numFicheiro );

ocs.executeQuery();

//                System.out.println(“CLO: ” + ocs.getObject(1));
//                System.out.println(“CLOB CLASS: ” + ocs.getObject(1).getClass());
//                System.out.println(“IMPORTED CLOB CLASS: ” + BLOB.class);

BLOB blob = null;
if (ocs.getObject(1) instanceof BLOB) {
blob = (BLOB) ocs.getObject(1);
}

content = new byte[ (int) blob.length()];
InputStream blobstream = blob.getBinaryStream();
try {
blobstream.read(content , 0 , (int) blob.length());
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
try {
blobstream.close();
} catch (Exception ignored) {}
}

return content;

} catch (SQLException sqlex) {
sqlex.printStackTrace();
throw sqlex;
} finally {
UtilsDB.close(ocs);
}

} catch (Exception daoe) {
Logger.getLogger(“pt.mapfre.pdf.dao”).
log(Level.SEVERE, “Erro na geracao de PDF”, daoe);
throw new BusinessException(daoe.getMessage() , daoe);
} finally {
UtilsDB.close(conn);
}

}
}

http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/oralob.htm#1043220

Deixe um Comentário

Ideias pró país…

Partilho convosco a ideia criativa que publiquei no site do criar2009.

Aqui vai o link:

http://videos.sapo.pt/UUHZNpMHHdZ4qy36ZkVV

Votem na ideia!

Deixe um Comentário

Google Desktop – connection refused error

Hello,

I had this problem with google desktop: Local querys were giving this error:The connection was refused when attempting to contact localhost:4664

I noticed that the problem was only on firefox, not IE. Then I found that the problem was an add-on called “Y-Slow” that was installed on my firefox and that was causing some incompatibility issue width google desktop.

Just disable every add-on in firefox when something starts smelling bad..

Deixe um Comentário

Source path too long error installing eclipse

Today I was trying to install Spring Source Tool Suite. Downloaded it and next step was simply extract the zip file (I’m using windows) to a folder.

The problem is that plugins in eclipse now use a very long pathname and that causes the extract tool in windows to give an error.

Winrar (the old version I use) also has the same problem. Solution: User 7-zip!

That’s all!

Deixe um Comentário

Hibernation not working in Vista ??

vista_hibernateI got this toshiba U400 with vista on it. It’s just the system that came with it… ok? So I also know that vista has issues, but I think that it also has come cool stuff, so I’m just waiting for Windows 7 like everyone else.. or just like many people. The last problem with my vista was that the hibernation thing, that I use heavly, stoped working.

This was a big problem because, I simply don’t like to wait for a all boot up every time I need to use the PC. So I suspected that the last update screw it up. I executed the restore program, to the moment before the last update and voilá! Hibernation is back again.vista_updates

Now, I changed the option to manual updates.

Finally, thanks to this site there’s another problem with my other PC that was due some file got wiped accidently. So enter command prompt width administrator and just execute: powercfg /hibernate on.

Problem solved!

hibernate

Deixe um Comentário

Spring JdbcTemplate calling Oracle store procedures or functions

After long long google search (My God! Why do we have to google for something that should be self-intuitive), I finally got my java program working  and calling a store procedure from Oracle.

The code before was this:

  /**
   *
   * @param connection
   * @param xml
   * @return
   * @throws SQLException
   */
  public String executaProcedimento (Connection connection,
                    String login,
                    String codPgm,
                    String xmlParams,
                    String urlWebAppServico)
  throws SQLException{

    CallableStatement
    stmt = connection.prepareCall(databaseObjects.STMT_F_EXEC_PROCEDIMENTO);
    //
    stmt.registerOutParameter(1, OracleTypes.VARCHAR);
    //
    stmt.setString(2, login);
    stmt.setString(3, codPgm);
    stmt.setString(4, xmlParams);
    stmt.setString(5, urlWebAppServico);
    stmt.execute();
    //System.out.println("xml:"+xml);
    String result = (String)stmt.getObject(1);

    stmt.close();
    return  result;

  }
  

And now a proud Spring equivallent one:

  /**
   *
   * @author Acacio Bernardo
   *
   */
  private class ProcedimentoTron
  extends StoredProcedure {

        private static final String SQL =
          "oracle_package_name.f_stored_function";

        public ProcedimentoTron(DataSource ds) {
            setDataSource(ds);
            setFunction(true);
            setSql(SQL);

            declareParameter(new SqlOutParameter("result", Types.VARCHAR));

            declareParameter(new SqlParameter   ("p_login", Types.VARCHAR));
            declareParameter(new SqlParameter   ("p_cod_pgm", Types.VARCHAR));
            declareParameter(new SqlParameter   ("p_xml_params", Types.VARCHAR));
            declareParameter(new SqlParameter   ("p_url_servico", Types.VARCHAR));

            compile();
        }

        public Map executa( String login,
                  String codPgm,
                  String xmlParams,
                  String urlWebAppServico) {
          //
          Map inputs = new HashMap();
            inputs.put("p_login", login);
            inputs.put("p_cod_pgm", codPgm);
            inputs.put("p_xml_params", xmlParams);
            inputs.put("p_url_servico", urlWebAppServico);
            return execute(inputs);
        }
    }

  /**
   *
   * @param connection
   * @param xml
   * @return
   * @throws SQLException
   */
  public String executaProcedimento (DataSource ds,
                    String login,
                    String codPgm,
                    String xmlParams,
                    String urlWebAppServico)
  throws SQLException{

    ProcedimentoTron proc =
         new ProcedimentoTron(ds);

    Map results = proc.executa(login, codPgm, xmlParams, urlWebAppServico);

    return  (String) results.get("result").toString();

  } 

The Oracle page where I found the information has an example, but it wasn't working because the order of the parameters was Wrong.
Is seems that first you must define the out parameter, and then the input parameters.

Deixe um Comentário

Trabalhar em J2EE

Andamos anos a estudar.

Lembro-me desde as aulas de educação visual até às de programação, estruturas de dados, redes.. para, no final, quando queremos comunicar nas reuniões, de forma eficaz, usamos técnicas tão sofisticadas como esta:

simuladores

simuladores

Deixe um Comentário

Interfaces e Classes

Quantas vezes já vos aconteceu estarem a analisar código java e, quando clicam num método, em vez do eclipse saltar para a implementação do mesmo, apresenta a interface porque é isso que na realidade está a ser referenciado. No entanto, o que se pretende é ver a implementação. Muito bem… É só fazer CTRL+T. E violá! O eclipse apresenta uma lista das classes que implementam aquele método. Como diria o Jamie Oliver…. Brilliant!

Deixe um Comentário

Firefox doesn’t open more than one window

Yes! Finally I found the problem that’s been nagging me for a long time!

Firefox wasn’t able to open more than one window. Doesn’t matter if I click CTRL+N or try to open another instance by executing the application from the desktop icon.

So the answer for me was: disable AVG extension. This was a huge fix because I’m so in to extensions, that I can’t use any other alternative like Chrome, until it allows gestures. For me is really much easier to browse with gestures than have to point an click throught close tab, back button, etc.firefox-extension

So here it is! Comment if it didin’t work for you (maybe  it’s another bad behavior extension).

Deixe um Comentário

Duas dicas de PLSQL

pl-sql

Para pesquisar objectos que contenham determinada expressão. (Como o grep no unix)

SELECT all_source.owner                                  ,
       all_source.TYPE                                   ,
       all_source.NAME                                   ,
       all_source.line                                   ,
       all_source.text                                   ,
       REPLACE(all_source.text,' ',NULL) TextoSinEspacios
  FROM all_source
 WHERE all_source.owner LIKE 'TRON%'
   AND all_source.TYPE    IN ('PROCEDURE','FUNCTION','PACKAGE','PACKAGE BODY')
   AND INSTR(UPPER(REPLACE(all_source.text,' ',NULL)),
       UPPER(REPLACE(REPLACE('&TextoParaComillaPoner#',' ',NULL)
       ,'#',''''))) != 0

Para escrever o caminho de execução sem ter que dar um erro. Ou seja, ver o stack trace de um programa em qualquer momento:

SUBSTR(DBMS_UTILITY.FORMAT_CALL_STACK,1,2000)

Deixe um Comentário

Posts Mais Antigos »