Skip Headers

Oracle® interMedia Java Classes User's Guide and Reference
Release 9.2
Part No. A96121-01
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback

Previous Next

2
Program Examples Using Java Classes

This chapter provides full-length examples of user-defined classes using interMedia Java Classes. Sample SQL scripts that demonstrate how to set up a schema on your database server are also included.

This code will not necessarily match the code shipped as AudioExample.java, DocumentExample.java, ImageExample.java, or VideoExample.java with the interMedia Java Classes installation. If you want to run an example on your system, use the files provided with the interMedia Java Classes installation; do not attempt to compile and run the code presented in this chapter.


Note:

This chapter contains examples of Java and SQL code. Some of the code examples display boldface numbers enclosed in brackets; these indicate that further explanation of that code will be in the numbered list immediately following the example.

2.1 OrdAudio Example

The audio example (including AudioExample.sql and AudioExample.java) contains user-defined methods that use SQL, JDBC, and interMedia Java Classes APIs to perform the following operations:

2.1.1 AudioExample.sql

Example 2-1 shows the complete contents of the AudioExample.sql sample file.

Example 2-1 Contents of AudioExample.sql

set echo on


-- PLEASE change system password
connect system/manager
drop user  AUDIOUSER cascade;


[1] create user AUDIOUSER identified by AUDIOUSER;
grant connect,resource to AUDIOUSER identified by AUDIOUSER;


[2] connect AUDIOUSER/AUDIOUSER


[3] CREATE TABLE TAUD(n NUMBER, aud ORDSYS.ORDAUDIO);


--
-- Note - the OrdAudio.init method was added in interMedia 8.1.7.
-- If you are running against an older release of interMedia and the 
-- Oracle database, you will have to modify the following INSERT statements
-- to use the OrdAudio default constructor.
--
[4] INSERT INTO TAUD VALUES(1, ORDSYS.ORDAudio.init( ));
INSERT INTO TAUD VALUES(2, ORDSYS.ORDAudio.init( ));
INSERT INTO TAUD VALUES(3, ORDSYS.ORDAudio.init( ));
commit;

The SQL statements in AudioExample.sql perform the following operations:

  1. Create a user named AUDIOUSER and grant the appropriate permissions to the user.

  2. Connect to the database server as AUDIOUSER.

  3. Create a table named TAUD with two columns: a column of numbers and a column of OrdAudio objects.

  4. Add three rows to the table, each containing an empty OrdAudio object.

See Oracle interMedia User's Guide and Reference for more information on the init method.

2.1.2 AudioExample.java

Section 2.1.2.1 through Section 2.1.2.8 show the methods contained in the AudioExample.java sample file.

2.1.2.1 main( ) Method

Example 2-2 shows the main( ) method.

Example 2-2 main( ) Method (Audio)

public static void main (String args[ ]){
     byte[ ] ctx = new byte[4000];
     OracleConnection con = null;
     try {
          AudioExample tk = new AudioExample( );
          [1] con = tk.connect( );
          //Include the following line only if you are running
          //an Oracle 8.1.7 database or later.
          //If you are running a database server prior to 8.1.7,
          //the call will fail.
          [2] OrdMediaUtil.imCompatibilityInit(con);
          [3] tk.loadDataFromFile(con);
          tk.extractProperties(con);
          tk.printProperties(con);
          tk.otherMethods(con);
          tk.loadDataFromStream(con);
          tk.loadDataFromByteArray(con);
          [4] con.commit( );
          [5] con.close( );
          System.out.println("Done.");
     }
     [6] catch (Exception e) {
          try {
               System.out.println("Exception : " + e);
               con.close( );
          }
          catch(Exception ex) {
               System.out.println("Close Connection Exception : " + ex);
          }
     }
}

The code in the main( ) method performs the following operations:

  1. Uses the connect( ) method to make a connection to a database table.

  2. Ensures the compatibility of your application with later releases of the Oracle database. See Section 1.8 for more information.

  3. Calls several methods (also defined in AudioExample.java) that manipulate objects on the database server and the local machine.

  4. Commits any changes made to the database table.

  5. Closes the connection to the database.

  6. Handles any errors or exceptions raised by the code.

Section 2.1.2.2 through Section 2.1.2.8 will provide information on the methods called from the main( ) method in the order in which they are called, not in the order they appear in AudioExample.java.

2.1.2.2 connect( ) Method

Example 2-3 shows a user-defined method named connect( ), which makes a connection from the application to the database.

Example 2-3 connect( ) Method (Audio)

public OracleConnection connect( ) throws Exception {
     String connectString;
     [1] Class.forName ("oracle.jdbc.driver.OracleDriver");
     [2] connectString = "jdbc:oracle:oci8:@";
     [3] OracleConnection con = (OracleConnection)DriverManager.getConnection
          (connectString,"AUDIOUSER","AUDIOUSER");
     [4] con.setAutoCommit(false);
     return con;
}

The connect( ) method performs the following operations:

  1. Loads the JDBC drivers directly, because the Oracle database uses a JDK-compliant Java Virtual Machine.

  2. Defines a string that contains the URL of the database to which you will connect. You may need to change this string to match your database.

  3. Sets the connection to the database, using the URL contained in connectString, the user name AUDIOUSER, and the password AUDIOUSER. The user name and password were created by AudioExample.sql.

  4. Disables the auto-commit mode. This means that you must commit or roll back manually with the commit( ) or rollback( ) methods, respectively.

2.1.2.3 loadDataFromFile( ) Method

Example 2-4 shows a user-defined method named loadDataFromFile( ), which uses the interMedia loadDataFromFile( ) method to populate the application object with media data.

Example 2-4 loadDataFromFile( ) Method (Audio)

public void loadDataFromFile(OracleConnection con) {
     try {
          [1] Statement s = con.createStatement( );
          [2] OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TAUD where n = 1 for update ");
          int index = 0;
          [3] while(rs.next( )){
               [4] index = rs.getInt(1);
               [5] OrdAudio audObj = (OrdAudio) rs.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [6] audObj.loadDataFromFile("testaud.dat");
               [7] audObj.getDataInFile("output1.dat");
               System.out.println("************AFTER getDataInFile ");
               [8] System.out.println(" getContentLength output : " +
                    audObj.getContentLength( ));
               [9] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update taud set aud = ? where 
                    n = " + index);
               stmt1.setCustomDatum(1,audObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("loading successful");
     }
     [10] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("loading unsuccessful");
     }
}

The loadDataFromFile( ) method performs the following operations:

  1. Creates an OracleStatement object.

  2. Executes the given SQL query and puts the results into a local OracleResultSet object. In this case, the SQL query selects the data in the database row where n=1.

  3. Performs the operations in the loop while there are results in the OracleResultSet that have not been processed. However, in this case, there is only one row included in the OracleResultSet, so the operations in the loop will run once.

  4. Sets an index variable to the value of the integer in the first column of the first row in the OracleResultSet (in this case, the value is 1).

  5. Creates a local OrdAudio object named audObj. Populates audObj with the contents of the OrdAudio object in the second column of the current row in the OracleResultSet.

  6. Uses the OrdAudio loadDataFromFile( ) method to load the media data in testaud.dat into the database OrdAudio object and into audObj. This also sets the local field on audObj, but not the database object.

  7. Uses the getDataInFile( ) method to get the media data from audObj and load it into a file on the local system named output1.dat.

  8. Gets the content length of audObj and prints it to the screen to verify the success of the loading.

  9. Creates and executes a SQL statement that will update the database OrdAudio object with the contents of audObj.

  10. Handles any errors or exceptions raised by the code.

2.1.2.4 extractProperties( ) Method

Example 2-5 shows a user-defined method named extractProperties( ), which sets the properties in the application object.

Example 2-5 extractProperties( ) Method (Audio)

public void extractProperties(OracleConnection con){
     byte[ ] ctx[ ] = new byte [4000][1];
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TAUD where n = 1 for update");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdAudio audObj = (OrdAudio) rs.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [2] audObj.setProperties(ctx);
               System.out.println("set Properties called");
               [3] if(audObj.checkProperties(ctx)){
                    System.out.println("checkProperties called");
                    System.out.println("setProperties successful");
                    System.out.println("checkProperties successful");
                    System.out.println("extraction  successful");
               }
               else{
                    System.out.println("checkProperties called");
                    System.out.println("extraction not successful");
                    System.out.println("checkProperties successful");
               }
               [4] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update taud set aud = ? 
                    where n = " + index);
               stmt1.setCustomDatum(1,audObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs.close( );
          s.close( );
     }
     [5] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("extract properties unsuccessful");
     }
}

The extractProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdAudio object named audObj, and populates audObj with media data through the same process described in steps 1 through 5 of Example 2-4. In this method, you will be operating on the contents of the second column of the row in the database table where n=1.

  2. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdAudio object. See "setProperties(byte[ ][ ])" in Chapter 3 for a list of the properties values extracted and set.

  3. Calls checkProperties( ) to compare the properties values in the application object with the values in the media data. If all values are the same, checkProperties( ) returns true and the appropriate messages are printed to the screen. If any values differ, checkProperties( ) returns false and the appropriate messages are printed to the screen.

  4. Creates and executes a SQL statement that will update the database OrdAudio object with the contents of audObj (including the properties extracted by setProperties( )).

  5. Handles any errors or exceptions raised by the code.

2.1.2.5 printProperties( ) Method

Example 2-6 shows a user-defined method named printProperties( ), which prints the attributes of the application object to the screen.

Example 2-6 printProperties( ) Method (Audio)

public void printProperties(OracleConnection con){
     try {
         [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)
               s.executeQuery("select * from TAUD where n = 1 ");
          int index = 0;
          while(rs.next( )) {
               index = rs.getInt(1);
               OrdAudio audObj = (OrdAudio) rs.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [2] System.out.println("format: " + audObj.getFormat( ));
               System.out.println("mimeType: " + audObj.getMimeType( ));
               System.out.println("encoding: " + audObj.getEncoding( ));
               System.out.println("numberOfChannels: " + 
                    audObj.getNumberOfChannels( ));
               System.out.println("samplingRate: " +
                    audObj.getSamplingRate( ));
               System.out.println("sampleSize: " + audObj.getSampleSize( ));
               System.out.println("compressionType : " +
                    audObj.getCompressionType( ));
               System.out.println("audioDuration: " +
                    audObj.getAudioDuration( ));
               System.out.println("description: " + audObj.getDescription( ));
          }
     }
     [3] catch(Exception e){
          System.out.println("exception raised " + e);
          System.out.println("print proerties unsuccessful");
     }
}

The printProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdAudio object named audObj, and populates audObj with media data through the same process described in steps 1 through 5 of Example 2-4. In this method, you will be operating on the contents of the second column of the row in the database table where n=1.

  2. Gets the values of the properties in audObj and prints them to the screen.

  3. Handles any errors or exceptions raised by the code.

2.1.2.6 otherMethods( ) Method

Example 2-7 shows a user-defined method named otherMethods( ), which attempts to use the processSourceCommand( ) method.

Example 2-7 otherMethods( ) Method (Audio)

public void otherMethods(OracleConnection con){
     byte[ ] ctx[ ] = {new byte[4000]};
     byte[ ] res[ ] = {new byte[20]};
     [1] int suc = 1;
     try {
          [2] Statement s1 = con.createStatement( );
          OracleResultSet rs1 = (OracleResultSet) s1.executeQuery
               ("select * from TAUD where n = 1 for update ");
          int index1 = 0;
          while(rs1.next( )) {
               index1 = rs1.getInt(1);
               OrdAudio audObj = (OrdAudio) rs1.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [3] try {
                    byte[ ] pSRes = audObj.processSourceCommand(ctx,
                         "", "", res);
                    suc = 0;
               }
               [4] catch (Exception e) { 
                    System.out.println("Expected Exception raised in 
                         processSourceCommand(...)" );
               }
               [5] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update taud set aud = ? where 
                    n = " + index1);
               stmt1.setCustomDatum(1,audObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs1.close( );
          s1.close( );
     }
     [6] catch(Exception e){
          System.out.println("Exception raised " );
     }
     [7] if(suc == 1)
          System.out.println("other methods successful");
     else
          System.out.println("other methods unsuccessful");
}

The otherMethods( ) method performs the following operations:

  1. Creates an integer that will be used to indicate the success or failure of the method and sets it initially to 1 (for success).

  2. Creates a statement, a local OracleResultSet, and a local OrdAudio object named audObj, and populates audObj with media data through the same process described in steps 1 through 5 of Example 2-4. In this method, you will be operating on the contents of the second column of the row in the database table where n=1.

  3. Tries to call processSourceCommand( ) with no value specified for the command to be called on the server side. This should raise an exception, which means the code following the processSourceCommand( ) call will not be run and the code in the catch loop will. If an exception is not raised, then the method has failed and the success indicator is set to 0 (for failure).

  4. Prints the expected exception that was raised in step 3.

  5. Creates and executes a SQL statement that will update the database OrdAudio object with the contents of audObj.

  6. Handles any unexpected errors or exceptions raised by the code.

  7. Prints the appropriate message to the screen based on the success or failure of the method.

2.1.2.7 loadDataFromStream( ) Method

Example 2-8 shows a user-defined method named loadDataFromStream( ), which uses the interMedia loadDataFromInputStream( ) method to load media data into the application object.

Example 2-8 loadDataFromStream( ) Method (Audio)

public void loadDataFromStream(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TAUD where n = 2 for update ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdAudio audObj = (OrdAudio) rs.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [2] FileInputStream fStream = new 
                    FileInputStream("testaud.dat");
               [3] audObj.loadDataFromInputStream(fStream);
               [4] audObj.getDataInFile("output2.dat");
               [5] fStream.close( );
               System.out.println("************AFTER getDataInFile ");
               [6] System.out.println(" getContentLength output : " +
                    audObj.getContentLength( ));
               [7] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update taud set aud = ? where
                    n = " + index);
               stmt1.setCustomDatum(1,audObj);
               stmt1.execute( );
               stmt1.close( );
          }
          System.out.println("load data from stream successful");
     }
     [8] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("load data from stream unsuccessful");
     }
}

The loadDataFromStream( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdAudio object named audObj, and populates audObj with media data through the same process described in steps 1 through 5 of Example 2-4. In this method, you will be operating on the contents of the second column of the row in the database table where n=2.

  2. Creates a new FileInputStream object. This input stream contains the contents of the local file testaud.dat.

  3. Uses the loadDataFromInputStream( ) method to load the media data in the input stream into the database OrdAudio object and into audObj. This also sets the local field on audObj, but not the database object.

  4. Uses the getDataInFile( ) method to get the media data from the application OrdAudio object and load it into a file on the local system named output2.dat.

  5. Closes the local input stream.

  6. Gets the content length of audObj and prints it to the screen to verify the success of the loading.

  7. Creates and executes a SQL statement that will update the database OrdAudio object with the contents of audObj. This update will set the attributes on the database object to match the application object.

  8. Handles any errors or exceptions raised by the code.

2.1.2.8 loadDataFromByteArray( ) Method

Example 2-9 shows a user-defined method named loadDataFromByteArray( ), which uses the interMedia loadDataFromByteArray( ) method to load media data into the application object.

Example 2-9 loadDataFromByteArray( ) Method (Audio)

public void loadDataFromByteArray(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TAUD where n = 3 for update ");
          int index = 0;
          while(rs.next( )) {
               index = rs.getInt(1);
               OrdAudio audObj = (OrdAudio) rs.getCustomDatum
                    (2, OrdAudio.getFactory( ));
               [2] File ff = new File("testaud.dat");
               int fileLength = (int) ff.length( );
               byte[ ] data = new byte[fileLength];
               [3] FileInputStream fStream = new
                    FileInputStream("testaud.dat");
               [4] fStream.read(data,0,fileLength);
               [5] audObj.loadDataFromByteArray(data);
               [6] fStream.close( );
               [7] audObj.getDataInFile("output3.dat");
               [8] byte[ ] resArr = audObj.getDataInByteArray( );
               [9] System.out.println("byte array length : " + 
                    resArr.length);
               [10] FileOutputStream outStream = new FileOutputStream
                    ("output4.dat");
               [11] outStream.write(resArr);
               [12] outStream.close( );
               [13] InputStream inpStream = audObj.getDataInStream( );
               int length = 32768;
               byte[ ] tempBuffer = new byte[32768];
               [14] int numRead = inpStream.read(tempBuffer,0,length);
               try {
                    [15] outStream = new FileOutputStream("output5.dat");
                    [16] while (numRead != -1) {
                         [17] if (numRead < 32768) {
                              length = numRead;
                              outStream.write(tempBuffer,0,length);
                              break;
                         }
                         [18] else
                              outStream.write(tempBuffer,0,length);
                         [19] numRead = inpStream.read(tempBuffer,0,length);
                    }
               }
               [20] finally {
                    outStream.close( );
                    inpStream.close( );
               }
               System.out.println("************AFTER getDataInFile ");
               [21] System.out.println("getContentLength output : " +
                    audObj.getContentLength( ));
               [22] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update taud set aud = ? where 
                    n = " + index);
               stmt1.setCustomDatum(1,audObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
     }
     [23] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("load data from byte array unsuccessful");
    }
}

The loadDataFromByteArray( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdAudio object named audObj, and populates audObj with media data through the same process described in steps 1 through 5 of Example 2-4. In this method, you will be operating on the contents of the second column of the row in the database table where n=3.

  2. Determines the size (in bytes) of the local file testaud.dat and creates a byte array of the same size.

  3. Creates a new FileInputStream object. This input stream contains the contents of testaud.dat.

  4. Reads the contents of the input stream into the byte array.

  5. Uses the loadDataFromByteArray( ) method to load the media data in the byte array into the database OrdAudio object and into audObj. This also sets the local field on audObj, but not the database object.

  6. Closes the input stream.

  7. Uses the getDataInFile( ) method to get the media data from the application OrdAudio object and load it into a file on the local system named output3.dat.

  8. Uses the getDataInByteArray( ) method to get the media data from the application OrdAudio object and load it into a local byte array named resArr.

  9. Gets the length of resArr and prints it to the screen to verify the success of the loading.

  10. Creates a new FileOutputStream object named outStream. This output stream will write data to a local file named output4.dat.

  11. Writes the contents of resArr to output4.dat.

  12. Closes the output stream.

  13. Creates a new input stream named inpStream. Uses the getDataInStream( ) method to get the media data from the application OrdAudio object and store it in inpStream.

  14. Reads 32768 bytes from the beginning (that is, at an offset of 0) of inpStream into the byte array tempBuffer. The integer numRead will be set to the total number of bytes read, or -1 if the end of the input stream has been reached. In this case, if loading is successful, numRead should be equal to 32768.

  15. Re-opens OutStream. In this case, it will write data to a local file named output5.dat.

  16. Runs the operations in the while loop if numRead is not equal to -1. The program should enter this loop.

  17. Enters the if loop if numRead is less than 32768 (that is, if all the data was read). The if loop will write the number of bytes read into tempBuffer into outStream, and then break out of the loop.

  18. Writes 32768 bytes into outStream if numRead is 32768.

  19. Attempts to read more data from the input stream into the byte array. If all data has been read successfully, then numRead will be set to -1 and the program will exit the loop. If there is still unread data in the input stream, then it will be read into the byte array and steps 17 and 18 will be repeated.

  20. Closes both the input stream and the output stream after exiting the while loop.

  21. Gets the content length of audObj and prints it to the screen to verify the success of the loading.

  22. Creates and executes a SQL statement that will update the database OrdAudio object with the contents of audObj. This update will set the attributes on the database object to match the application object.

  23. Handles any errors or exceptions raised by the code.

2.2 OrdDoc Example

The OrdDoc example (including DocumentExample.sql and DocumentExample.java) contains user-defined methods that use SQL, JDBC, and interMedia Java Classes APIs to perform the following operations:

2.2.1 DocumentExample.sql

Example 2-10 shows the complete contents of the DocumentExample.sql sample file.

Example 2-10 Contents of DocumentExample.sql

set echo on


--PLEASE change system password
connect system/manager
drop user DOCUSER cascade;


[1] create user DOCUSER identified by DOCUSER ;
grant connect,resource to DOCUSER identified by DOCUSER;


[2] connect DOCUSER/DOCUSER


[3] CREATE TABLE TDOC(n NUMBER, doc ORDSYS.ORDDOC);


[4] INSERT INTO TDOC VALUES(1, ORDSYS.ORDDoc.init( ));
INSERT INTO TDOC VALUES(2, ORDSYS.ORDDoc.init( ));
INSERT INTO TDOC VALUES(3, ORDSYS.ORDDoc.init( ));


commit;

The SQL statements in DocumentExample.sql perform the following operations:

  1. Create a user named DOCUSER and grant the appropriate permissions to the user.

  2. Connect to the database server as DOCUSER.

  3. Create a table named TDOC with two columns: a column of numbers and a column of OrdDoc objects.

  4. Add three rows to the table, each containing an empty OrdDoc object.

2.2.2 DocumentExample.java

Section 2.2.2.1 through Section 2.2.2.8 show the methods defined in the DocumentExample.java sample file.

2.2.2.1 main( ) Method

Example 2-11 shows the contents of the main( ) method.

Example 2-11 main( ) Method (Doc)

public static void main (String args[ ]){
     byte[ ] ctx = new byte[4000];
     OracleConnection con = null;
     try {
          DocumentExample tk = new DocumentExample( );
          [1] con = tk.connect( );
          [2] OrdMediaUtil.imCompatibilityInit(con);
          [3] tk.loadDataFromFile(con);
          tk.extractProperties(con);
          tk.printProperties(con);
          tk.loadDataFromStream(con);
          tk.otherMethods(con);
          tk.loadDataFromByteArray(con);
          [4] con.commit( );
          [5] con.close( );
          System.out.println("Done.");
     }
     [6] catch (Exception e) {
          try {
               System.out.println("Exception : " + e);
               con.close( );
          }
          catch(Exception ex) {
          System.out.println("Close Connection Exception : " + ex);
          }
     }
}

The code in the main( ) method performs the following operations:

  1. Uses the connect( ) method to make a connection to a database table.

  2. Ensures the compatibility of your application with later releases of the Oracle database. See Section 1.8 for more information.

  3. Calls several methods (also defined in DocumentExample.java) that manipulate objects on the database server and the local machine.

  4. Commits any changes made to the database table.

  5. Closes the connection to the database.

  6. Handles any errors or exceptions raised by the code.

Section 2.2.2.2 through Section 2.2.2.8 will provide information on the methods called from the main( ) method in the order in which they are called, not in the order they appear in DocumentExample.java.

2.2.2.2 connect( ) Method

Example 2-12 shows a user-defined method named connect( ), which makes a connection from an application to a database.

Example 2-12 connect( ) Method (Doc)

public OracleConnection connect( ) throws Exception{
     String connectString;
     [1] Class.forName ("oracle.jdbc.driver.OracleDriver");
     [2] connectString = "jdbc:oracle:oci8:@";
     [3] OracleConnection con = (OracleConnection) 
          DriverManager.getConnection(connectString,"DOCUSER","DOCUSER");
     [4] con.setAutoCommit(false);
     return con;
}

The connect( ) method performs the following operations:

  1. Loads the JDBC drivers directly, because the Oracle database uses a JDK-compliant Java virtual machine.

  2. Defines a string that contains the URL of the database to which you will connect. You may need to change this string to match your database.

  3. Sets the connection to the database, using the URL contained in connectString, the user name DOCUSER, and the password DOCUSER. The user name and password were created by DocumentExample.sql.

  4. Disables the auto-commit mode. This means that you must commit or roll back manually with the commit( ) or rollback( ) methods, respectively.

2.2.2.3 loadDataFromFile( ) Method

Example 2-13 shows a user-defined method named loadDataFromFile( ), which uses the interMedia loadDataFromFile( ) method to populate the application object with media data.

Example 2-13 loadDataFromFile( ) Method (Doc)

public void loadDataFromFile(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          [2] OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TDOC where n = 1 for update");
          int index = 0;
          [3] while(rs.next( )){
               [4] index = rs.getInt(1);
               [5] OrdDoc docObj = (OrdDoc) rs.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [6] docObj.loadDataFromFile("testaud.dat");
               [7] docObj.getDataInFile("output1.dat");
               System.out.println("************AFTER getDataInFile ");
               [8] System.out.println("getContentLength output: " + 
                    docObj.getContent( ).length( ));
               [9] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tdoc set doc = ? where n = " + 
                    index);
               stmt1.setCustomDatum(1,docObj);
               stmt1.execute( );
               stmt1.close( );
          }
     System.out.println("loading successful");
     }
     [10] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("loading unsuccessful");
     }
}

The loadDataFromFile( ) method performs the following operations:

  1. Creates an OracleStatement object.

  2. Executes the given SQL query and puts the results into a local OracleResultSet object. In this case, the SQL query selects the data in the database row where n=1.

  3. Performs the operations in the loop while there are results in the OracleResultSet that have not been processed. However, in this case, there is only one row included in the OracleResultSet, so the operations in the loop will run once.

  4. Sets an index variable to the value of the integer in the first column of the first row in the OracleResultSet (in this case, the value is 1).

  5. Creates a local OrdDoc object named docObj. Populates docObj with the contents of the OrdDoc object in the second column of the current row in the OracleResultSet.

  6. Uses the OrdDoc loadDataFromFile( ) method to load the media data in testaud.dat into the database OrdDoc object and into docObj. This also sets the local field on docObj, but not the database object.

  7. Uses the getDataInFile( ) method to get the media data from docObj and load it into a file on the local system named output1.dat.

  8. Gets the content length of docObj and prints it to the screen to verify the success of the loading.

  9. Creates and executes a SQL statement that will update the database OrdDoc object with the contents of docObj.

  10. Handles any errors or exceptions raised by the code.

2.2.2.4 extractProperties( ) Method

Example 2-14 shows a user-defined method named extractProperties( ), which sets the properties in the application object.

Example 2-14 extractProperties( ) Method (Doc)

public void extractProperties(OracleConnection con){
     byte[ ] ctx[ ] = new byte [4000][1];
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)
          s.executeQuery("select * from TDOC where n = 1 for update");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdDoc docObj = (OrdDoc)rs.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [2] docObj.setProperties(ctx,false);
               System.out.println("setProperties successful");
               [3] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tdoc set doc = ? where n = " + 
                    index);
               stmt1.setCustomDatum(1,docObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs.close( );
          s.close( );
     }
     [4] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("extract prop unsuccessful");
     }
}

The extractProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdDoc object named docObj, and populates docObj with media data through the same process described in steps 1 through 5 of Example 2-13. In this method, you will be operating on the contents of the row where n=1.

  2. Calls setProperties to extract properties values from the media data and set them in the application OrdDoc object. See "setProperties( )" in Chapter 4 for a list of the properties values extracted and set.

  3. Creates and executes a SQL statement that will update the database OrdDoc object with the contents of docObj (including the properties extracted by setProperties( )).

  4. Handles any exceptions or errors raised by the code.

2.2.2.5 printProperties( ) Method

Example 2-15 shows a user-defined method named printProperties( ), which prints the attributes of the application object to the screen.

Example 2-15 printProperties( ) Method (Doc)

public void printProperties(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery("select * from
               TDOC where n = 1 ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdDoc docObj = (OrdDoc) rs.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [2] System.out.println("format: " + docObj.getFormat( ));
               System.out.println("mimetype: " + docObj.getMimeType( ));
               System.out.println("contentlength: " + 
                    docObj.getContentLength( ));
          }
     }
     [3] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("print properties unsuccessful");
     }
}

The printProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdDoc object named docObj, and populates docObj with media data through the same process described in steps 1 through 5 of Example 2-13. In this method, you will be operating on the contents of the row where n=1.

  2. Gets the values of the properties of docObj and prints them to the screen.

  3. Handles any exceptions raised by the code.

2.2.2.6 loadDataFromStream( ) Method

Example 2-16 shows a user-defined method named loadDataFromStream( ), which uses the interMedia loadDataFromInputStream( ) method to load media data into the application object.

Example 2-16 loadDataFromStream( ) Method (Doc)

public void loadDataFromStream(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery("select * from
               TDOC where n = 2 for update ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdDoc docObj = (OrdDoc) rs.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [2] FileInputStream  fStream  = new FileInputStream
                    ("testaud.dat");
               [3] docObj.loadDataFromInputStream(fStream);
               [4] docObj.getDataInFile("output2.dat");
               [5] fStream.close( );
               System.out.println("************AFTER getDataInFile ");
               [6] System.out.println("getContentLength output: " + 
               docObj.getContent( ).length( ));
               [7] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tdoc set doc = ? where n = " + 
                    index);
               stmt1.setCustomDatum(1,docObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("load data from stream successful");
     }
     [8] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("load data from stream unsuccessful");
     }
}

The loadDataFromStream( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdDoc object named docObj, and populates docObj with media data through the same process described in steps 1 through 5 of Example 2-13. In this method, you will be operating on the contents of the row where n=2.

  2. Creates a new FileInputStream object. This input stream contains the contents of the local file testaud.dat.

  3. Uses the loadDataFromInputStream( ) method to load the media data in the input stream into the database OrdDoc object and into docObj. This also sets the local field on docObj, but not the database object.

  4. Uses the getDataInFile( ) method to get the media data from the application OrdDoc object and load it into a file on the local system named output2.dat.

  5. Closes the local input stream.

  6. Gets the content length of docObj and prints it to the screen to verify the success of the loading.

  7. Creates and executes a SQL statement that will update the database OrdDoc object with the contents of docObj. This update will set the attributes on the database object to match the application object.

  8. Handles any errors or exceptions raised by the code.

2.2.2.7 otherMethods( ) Method

Example 2-17 shows a user-defined method named otherMethods( ), which attempts to use the processSourceCommand( ) method.

Example 2-17 otherMethods( ) Method (Doc)

public void otherMethods(OracleConnection con){
     byte[ ] ctx[ ] = {new byte[4000]};
     byte[ ] res[ ] = {new byte[20]};
     [1] int suc = 1;
     try {
          [2] Statement s1 = con.createStatement( );
          OracleResultSet rs1 = (OracleResultSet)
          s1.executeQuery("select * from TDOC where n = 1 for update ");
          int index1 = 0;
          while(rs1.next( )){
               index1 = rs1.getInt(1);
               OrdDoc docObj = (OrdDoc) rs1.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [3] try {
                    byte[ ] pSRes = docObj.processSourceCommand(ctx, "", "", 
                         res);
                    suc = 0;
               }
               [4] catch (Exception e) { 
                    System.out.println("Expected Exception raised in 
                         processSourceCommand(...)" );
               }
               [5] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tdoc set doc = ? where n = " + 
                    index1);
               stmt1.setCustomDatum(1,docObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs1.close( );
          s1.close( );
     }
     [6] catch(Exception e){
          System.out.println("Exception raised " );
     }
     [7] if(suc ==1)
          System.out.println("other methods successful");
     else
          System.out.println("other methods unsuccessful");
}

The otherMethods( ) method performs the following operations:

  1. Creates an integer that will be used to indicate the success or failure of the method and sets it initially to 1 (for success).

  2. Creates a statement, a local OracleResultSet, and a local OrdDoc object named docObj, and populates docObj with media data through the same process described in steps 1 through 5 of Example 2-13. In this method, you will be operating on the contents of the row where n=1.

  3. Tries to call processSourceCommand( ) with no value specified for the command to be called on the server side. This should raise an exception, which means the code following the processSourceCommand( ) call will not be run and the code in the catch loop will. If an exception is not raised, then the method has failed and the success indicator is set to 0 (for failure).

  4. Prints the expected exception that was raised in step 3.

  5. Creates and executes a SQL statement that will update the database OrdDoc object with the contents of docObj.

  6. Handles any unexpected errors or exceptions raised by the code.

  7. Prints the appropriate message to the screen based on the success or failure of the method.

2.2.2.8 loadDataFromByteArray( ) Method

Example 2-18 shows a user-defined method named loadDataFromByteArray( ), which uses the interMedia loadDataFromByteArray( ) method to load media data into the application object.

Example 2-18 loadDataFromByteArray( ) Method (Doc)

public void loadDataFromByteArray(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery("select * from
               TDOC where n = 3 for update ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdDoc docObj = (OrdDoc) rs.getCustomDatum(2, 
                    OrdDoc.getFactory( ));
               [2] File ff = new File("testaud.dat");
               int fileLength = (int) ff.length( );
               byte[ ] data = new byte[fileLength];
               [3] FileInputStream  fStream  = new FileInputStream
                    ("testaud.dat");
               [4] fStream.read(data,0,fileLength);
               [5] docObj.loadDataFromByteArray(data);
               [6] fStream.close( );
               [7] docObj.getDataInFile("output3.dat");
               [8] byte[ ] resArr = docObj.getDataInByteArray( );
               [9] System.out.println("byte array length: " + resArr.length);
               [10] FileOutputStream outStream = new FileOutputStream
                    ("output4.dat");
               [11] outStream.write(resArr);
               [12] outStream.close( );
               [13] InputStream inpStream = docObj.getDataInStream( );
               int length = 32768;
               byte[ ] tempBuffer = new byte[32768];
               [14] int numRead = inpStream.read(tempBuffer,0,length);
               try {
                    [15] outStream = new FileOutputStream("output5.dat");
                    [16] while(numRead != -1) {
                         [17] if (numRead < 32768) {
                              length = numRead;
                              outStream.write(tempBuffer,0,length);
                              break;
                         } 
                         [18] else
                              outStream.write(tempBuffer,0,length);
                         [19] numRead = inpStream.read(tempBuffer,0,length);
                    }
               }
               [20] finally {
                    outStream.close( );
                    inpStream.close( );
               }
               System.out.println("************AFTER getDataInFile ");
               [21] System.out.println("getContentLength output: " +
                    docObj.getContent( ).length( ));
               [22] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tdoc set doc = ? where n = " +
                    index);
               stmt1.setCustomDatum(1,docObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
     }
     [23] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("loadData from byte array unsuccessful");
     }
}

The loadDataFromByteArray( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdDoc object named docObj, and populates docObj with media data through the same process described in steps 1 through 5 of Example 2-13. In this method, you will be operating on the contents of the row where n=3.

  2. Determines the size (in bytes) of the local file testaud.dat and creates a byte array of the same size.

  3. Creates a new FileInputStream object. This input stream contains the contents of testaud.dat.

  4. Reads the contents of the input stream into the byte array.

  5. Uses the loadDataFromByteArray( ) method to load the media data in the byte array into the database OrdDoc object and into docObj. This also sets the local field on docObj, but not the database object.

  6. Closes the input stream.

  7. Uses the getDataInFile( ) method to get the media data from the application OrdDoc object and load it into a file on the local system named output3.dat.

  8. Uses the getDataInByteArray( ) method to get the media data from the application OrdDoc object and load it into a local byte array named resArr.

  9. Gets the length of resArr and prints it to the screen to verify the success of the loading.

  10. Creates a new FileOutputStream object named outStream. This output stream will write data to a local file named output4.dat.

  11. Writes the contents of resArr to output4.dat.

  12. Closes the output stream.

  13. Creates a new input stream named inpStream. Uses the getDataInStream( ) method to get the media data from the application OrdDoc object and store it in inpStream.

  14. Reads 32768 bytes from the beginning (that is, at an offset of 0) of inpStream into the byte array tempBuffer. The integer numRead will be set to the total number of bytes read, or -1 if the end of the input stream has been reached. In this case, if loading is successful, numRead should be equal to 32768.

  15. Re-opens OutStream. In this case, it will write data to a local file named output5.dat.

  16. Runs the operations in the while loop if numRead is not equal to -1. The program should enter this loop.

  17. Enters the if loop if numRead is less than 32768 (that is, if all the data was read). The if loop will write the number of bytes read into tempBuffer into outStream, and then break out of the loop.

  18. Writes 32768 bytes into outStream if numRead is 32768.

  19. Attempts to read more data from the input stream into the byte array. If all data has been read successfully, then numRead will be set to -1 and the program will exit the loop. If there is still unread data in the input stream, then it will be read into the byte array and steps 17 and 18 will be repeated.

  20. Closes both the input stream and the output stream after exiting the while loop.

  21. Gets the content length of docObj and prints it to the screen to verify the success of the loading.

  22. Creates and executes a SQL statement that will update the database OrdDoc object with the contents of docObj. This update will set the attributes on the database object to match the application object.

  23. Handles any errors or exceptions raised by the code.

2.3 OrdImage Example

The image example (including ImageExample.sql and ImageExample.java) contains user-defined methods that use SQL, JDBC, and interMedia Java Classes APIs to perform the following operations:

2.3.1 ImageExample.sql

Example 2-19 shows the contents of ImageExample.sql.

Example 2-19 Contents of ImageExample.sql

set echo on


-- Please Change system password.
connect / as sysdba;
drop user IMAGEUSER cascade;


[1] grant connect,resource to IMAGEUSER identified by IMAGEUSER;


-- Replace C:\Oracle\Ora' with your ORACLE HOME
[2] create or replace directory ORDIMAGEDIR as 'C:\Oracle\Ora\ord\img\demo';
grant read on directory ORDIMAGEDIR to public with grant option;


[3] connect IMAGEUSER/IMAGEUSER;


[4] create table ordimagetab(id number, image ORDSYS.ORDImage, image2 ORDSYS.ORDImage);


-- Note - the OrdImage.init method was added in interMedia 8.1.7.
-- If you are running against an older release of interMedia and the
-- Oracle database, you will have to modify the following INSERT statements
-- to use the OrdImage default constructor.
--
[5] insert into ordimagetab values
(1, ORDSYS.ORDImage.init( ),
    ORDSYS.ORDImage.init( ));


insert into ordimagetab values
(2, ORDSYS.ORDImage.init( ),
    ORDSYS.ORDImage.init( ));


insert into ordimagetab values
(3, ORDSYS.ORDImage.init( ),
    ORDSYS.ORDImage.init( ));


insert into ordimagetab values
(4, ORDSYS.ORDImage.init( ),
    ORDSYS.ORDImage.init( ));


[6] insert into ordimagetab values
(5, ORDSYS.ORDImage.init('file','ORDIMAGEDIR','imgdemo.dat'),
    ORDSYS.ORDImage.init( ));


insert into ordimagetab values
(6, ORDSYS.ORDImage.init('file','ORDIMAGEDIR','imgdemo.dat'),
    ORDSYS.ORDImage.init( ));


[7] insert into ordimagetab values
(10, ORDSYS.ORDImage.init('file','ORDIMAGEDIR','cbrdemo1.dat'),
     ORDSYS.ORDImage.init( ));
[8] insert into ordimagetab values
(11, ORDSYS.ORDImage.init('file','ORDIMAGEDIR','cbrdemo2.dat'),
     ORDSYS.ORDImage.init( ));


[9] create table sigtable(id number, sig ORDSYS.ORDImageSignature);


[10] insert into sigtable values
(10, ORDSYS.ORDImageSignature.init( ));
insert into sigtable values
(11, ORDSYS.ORDImageSignature.init( ));


commit;
set echo off
exit;

The SQL statements in ImageExample.sql perform the following operations:

  1. Create a user named IMAGEUSER and grant the appropriate permissions to the user.

  2. Create a directory named ORDIMAGEDIR and set the appropriate permissions. You will need to change the directory to match your Oracle home.

  3. Connect to the database server as IMAGEUSER.

  4. Create a table named ordimagetab, which contains one column of numbers and two columns of OrdImage objects.

  5. Using the init method, add four rows with two empty objects each.

  6. Using the init method, add two rows with one object based on imgdemo.dat and one empty object.

  7. Using the init method, add a row with one object based on cbrdemo1.dat and one empty object.

  8. Using the init method, add a row with one object based on cbrdemo2.dat and one empty object.

  9. Create a table named sigtable, which contains one column of numbers and one column of OrdImageSignature numbers.

  10. Using the init method, add two rows with an empty OrdImageSignature object.

See Oracle interMedia User's Guide and Reference for more information on the init method.

2.3.2 ImageExample.java

Section 2.3.2.1 through Section 2.3.2.12 show the methods contained in the ImageExample.java sample file.

2.3.2.1 main( ) Method

Example 2-20 shows the main( ) method.

Example 2-20 main( ) Method (Image)

public static void main (String args[ ]){
     byte[ ] ctx = new byte[4000];
     OracleConnection con = null;
     try{
          ImageExample ie = new ImageExample( );
          [1] con = ie.connect( );
          //Include the following line only if you are running
          //an Oracle 8.1.7 database or later.
          //If you are running a database server prior to 8.1.7,
          //the call will fail.
          [2] OrdMediaUtil.imCompatibilityInit(con);
          [3] ie.setPropertiesExample(con);
          ie.displayPropertiesExample(con);
          ie.fileBasedExample(con);
          ie.streamBasedExample(con);
          ie.byteArrayBasedExample(con);
          ie.processExample(con);
          [4] ie.sigGeneration(con);
          ie.sigSimilarity(con);
          ie.imageMatchingScore(con);
          [5] con.commit( );
          [6] con.close( );
          System.out.println("Done.");
     }
     [7] catch (Exception e){
          try{
               System.out.println("Exception : " + e);
               con.close( );
          }
          catch(Exception ex){
               System.out.println("Close Connection Exception : " + ex);
          }
     }
}

The code in the main( ) method performs the following operations:

  1. Uses the connect( ) method to make a connection to a database table.

  2. Ensures the compatibility of your application with later releases of the Oracle database. See Section 1.8 for more information.

  3. Calls several methods (also defined in ImageExample.java) that manipulate objects on the database server and the local machine.

  4. Calls several methods (also defined in ImageExample.java) that test the OrdImageSignature object.

  5. Commits any changes made to the database table.

  6. Closes the connection to the database.

  7. Handles any errors or exceptions raised by the code.

Section 2.3.2.2 through Section 2.3.2.12 will provide information on the methods called from the main( ) method.

2.3.2.2 connect( )Method

Example 2-21 shows a user-defined method named connect( ), which makes a connection from the application to the database.

Example 2-21 connect( ) Method (Image)

public OracleConnection connect( ) throws Exception{
     String connectString;
     [1] Class.forName ("oracle.jdbc.driver.OracleDriver");
     [2] connectString = "jdbc:oracle:oci8:@";
     [3] OracleConnection con = (OracleConnection)DriverManager.getConnection
          (connectString,"IMAGEUSER","IMAGEUSER");
     [4] con.setAutoCommit(false);
     return con;
}

The connect( ) method performs the following operations:

  1. Loads the JDBC drivers directly, because the Oracle database uses a JDK-compliant Java virtual machine.

  2. Defines a string that contains the URL of the database to which you will connect. You may need to change this string to match your database.

  3. Sets the connection to the database, using the URL contained in connectString, the user name IMAGEUSER, and the password IMAGEUSER. The user name and password were created by ImageExample.sql.

  4. Disables the auto-commit mode. This means that you must commit or roll back manually with the commit( ) or rollback( ) methods, respectively.

2.3.2.3 setPropertiesExample( ) Method

Example 2-22 shows a user-defined method named setPropertiesExample( ), which sets the properties in the application object.

Example 2-22 setPropertiesExample( ) Method (Image)

public void setPropertiesExample(OracleConnection con){
     try{
          int index = 0;
          [1] Statement s = con.createStatement( );
          [2] OracleResultSet rs = (OracleResultSet)s.executeQuery
               ("select * from ordimagetab where id = 5 for update");
          [3] while(rs.next( )){
               [4] index = rs.getInt(1);
               [5] OrdImage imgObj = (OrdImage)rs.getCustomDatum
                    (2, OrdImage.getFactory( ));
               [6] imgObj.setProperties( );
               System.out.println("set Properties called");
               [7] if(imgObj.checkProperties( )){
                    System.out.println("checkProperties called");
                    System.out.println("setProperties successful");
                    System.out.println("checkProperties successful");
                    System.out.println("successful");
               }
               else{
                    System.out.println("checkProperties called");
                    System.out.println("setProperties not successful");
                    System.out.println("checkProperties successful");
               }
               [8] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update ordimagetab set 
                    image = ? where id = " + index);
               stmt1.setCustomDatum(1,imgObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs.close( );
          s.close( );
     }
     [9] catch(Exception e){
          System.out.println("exception raised " + e);
     }
}

The setPropertiesExample( ) method performs the following operations:

  1. Creates an OracleStatement object.

  2. Executes the given SQL query and puts the results into a local OracleResultSet object. In this case, the SQL query selects the data in the database row where id=5.

  3. Performs the operations in the loop while there are results in the OracleResultSet that have not been processed. However, in this case, there is only one row included in the OracleResultSet, so the operations in the loop will run once.

  4. Sets an index variable to the value of the integer in the first column of the first row in the OracleResultSet (in this case, the value is 5).

  5. Creates a local OrdImage object named imgObj. Populates imgObj with the contents of the OrdImage object in the second column of the current row in the OracleResultSet.

  6. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdImage object. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  7. Calls checkProperties( ) to compare the properties values in the application object with the values in the media data. If all values are the same, checkProperties( ) returns true and the appropriate messages are printed to the screen. If any values differ, checkProperties( ) returns false and the appropriate messages are printed to the screen.

  8. Creates and executes a SQL statement that will update the database OrdImage object with the contents of imgObj.

  9. Handles any errors or exceptions raised by the code.

2.3.2.4 displayPropertiesExample( ) Method

Example 2-23 shows a user-defined method named displayPropertiesExample( ), which prints the attributes of the application object to the screen.

Example 2-23 displayPropertiesExample( ) Method (Image)

public void displayPropertiesExample(OracleConnection con){
     try{
          int index = 0;
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery(
               "select * from ordimagetab where id = 5 ");
          while(rs.next( )){
               index = rs.getInt(1);
               OrdImage imgObj = (OrdImage) rs.getCustomDatum(2,
                    OrdImage.getFactory( ));
               [2] System.out.println("format : " + imgObj.getFormat( ));
               System.out.println("mimeType: " + imgObj.getMimeType( ));
               System.out.println("height: " + imgObj.getHeight( ));
               System.out.println("width: " + imgObj.getWidth( ));
               System.out.println("contentLength: " +
                    imgObj.getContentLength( ));
               System.out.println("contentFormat: " +
                    imgObj.getContentFormat( ));
               System.out.println("compressionFormat: " +
                    imgObj.getCompressionFormat( ));
               System.out.println("source type: " + 
                    imgObj.getSourceType( ));
               System.out.println("source loc: " +
                    imgObj.getSourceLocation( ));
               System.out.println("source name: " + imgObj.getSourceName( ));
               System.out.println("source : " + imgObj.getSource( ));
               [3] try{
                    String attrString = getAllAttributesAsString(imgObj);
                    System.out.println(attrString);
               }
               [4] catch (Exception e){
                    System.out.println("Exception raised in
                         getAllAttributesAsString:");
               }
               System.out.println("successful");
          }
     }
     [5] catch(Exception e) {
          System.out.println("exception raised " + e);
     }
}

The displayPropertiesExample( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdImage object named imgObj, and populates imgObj with media data through the same process described in steps 1 through 5 of Example 2-22. In this method, you will be operating on the contents of the row where id=5. This is the same row you operated on in Example 2-22.

  2. Gets the values of the properties in imgObj and prints them to the screen.

  3. Gets the attributes of imgObj and stores them in a string by using the getAllAttributesAsString( ) method, and prints the contents of the string to the screen. See Section 2.3.2.5 for more information on getAllAttributesAsString( ).

  4. Handles any errors or exceptions raised by the call to getAllAttributesAsString( ).

  5. Handles any errors or exceptions raised by the code in general.

2.3.2.5 getAllAttributesAsString( ) Method

Example 2-24 shows a user-defined method named getAllAttributesAsString( ), which creates a String object that contains the values of the application object attributes.

Example 2-24 getAllAttributesAsString( ) Method (Image)

public String getAllAttributesAsString (OrdImage imgObj) throws Exception{
     [1] String attStr = imgObj.getSource( ) + " mimeType = " +
          imgObj.getMimeType( ) + ", fileFormat = " + 
          imgObj.getFormat( ) + ", height = " + imgObj.getHeight( )
          + ", width = " + imgObj.getWidth( ) + ", contentLength = "
          + imgObj.getContentLength( ) + ", contentFormat = " +
          imgObj.getContentFormat( ) + ", compressionFormat = " +
          imgObj.getCompressionFormat( );
     [2] return attStr;
}

The getAllAttributesAsString( ) method performs the following operations:

  1. Creates a String object named attStr. Gets the values of several attributes from the application image object and stores their values in attStr.

  2. Returns attStr to the method that called this method.

2.3.2.6 fileBasedExample( ) Method

Example 2-25 shows a user-defined method named fileBasedExample( ), which uses the loadDataFromFile( ) method to load media data into the application object.

Example 2-25 fileBasedExample( ) Method (Image)

public void fileBasedExample(OracleConnection con){
     try{
          int index = 0;
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery(
               "select * from ORDIMAGETAB where id = 2 for update ");
          while(rs.next( )){
               index = rs.getInt(1);
               OrdImage imgObj = (OrdImage) rs.getCustomDatum(2,
                    OrdImage.getFactory( ));
               [2] imgObj.loadDataFromFile("imgdemo.dat");
               [3] imgObj.setProperties( );
               [4] imgObj.getDataInFile("fileexample.dat");
               [5] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update ordimagetab set image =
                    ? where id = " + index);
               stmt1.setCustomDatum(1,imgObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("successful");
     }
     [6] catch(Exception e){
          System.out.println("exception raised " + e);
     }
}

The fileBasedExample( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdImage object named imgObj, and populates imgObj with media data through the same process described in steps 1 through 5 of Example 2-22. In this method, you will be operating on the contents of the row where id=2.

  2. Uses the loadDataFromFile( ) method to load the media data from the local file imgdemo.dat into the database OrdImage object and into imgObj. This also sets the local field on imgObj, but not the database object.

  3. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdImage object. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  4. Uses the getDataInFile( ) method to get the media data from the application OrdImage object and load it into a file on the local system named fileexample.dat.

  5. Creates and executes a SQL statement that will update the database OrdImage object with the contents of imgObj. This update will set the attributes on the database object, to match the application object.

  6. Handles any errors or exceptions raised by the code.

2.3.2.7 streamBasedExample( ) Method

Example 2-26 shows a user-defined method named streamBasedExample( ), which uses the loadDataFromInputStream( ) method to load media data into the application object.

Example 2-26 streamBasedExample( ) Method (Image)

public void streamBasedExample(OracleConnection con){
     try{
          int index = 0;
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery(
               "select * from ORDIMAGETAB where id = 3 for update ");
          while(rs.next( )){
               index = rs.getInt(1);
               OrdImage imgObj = (OrdImage) rs.getCustomDatum(2,
                    OrdImage.getFactory( ));
               [2] FileInputStream fStream = new FileInputStream
                    ("imgdemo.dat");
               [3] imgObj.loadDataFromInputStream(fStream);
               [4] fStream.close( );
               [5] imgObj.setProperties( );
               [6] InputStream inpStream = imgObj.getDataInStream( );
               int length = 32300;
               byte[ ] tempBuffer = new byte[length];
               [7] int numRead = inpStream.read(tempBuffer,0,length);
               FileOutputStream outStream=null;
               try{
                    [8] outStream = new FileOutputStream
                         ("streamexample.dat");
                    [9] while(numRead != -1){
                         [10] if (numRead < length){
                              length = numRead;
                              outStream.write(tempBuffer,0,length);
                              break;
                         }
                         [11] else
                              outStream.write(tempBuffer,0,length);
                         [12] numRead = inpStream.read(tempBuffer,0,
                              length);
                    }
               }
               [13] finally{
                    if (outStream != null)
                         outStream.close( );
                    inpStream.close( );
               }
               [14] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update ordimagetab set 
                    image = ? where id = " + index);
               stmt1.setCustomDatum(1,imgObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("successful");
     }
     [15] catch(Exception e){
          System.out.println("exception raised " + e);
     }
}

The streamBasedExample( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdImage object named imgObj, and populates imgObj with media data through the same process described in steps 1 through 5 of Example 2-22. In this method, you will be operating on the contents of the row where id=3.

  2. Creates a new FileInputStream object. This input stream contains the contents of the local file imgdemo.dat.

  3. Uses the loadDataFromInputStream( ) method to load the media data in the input stream into the database OrdImage object and into imgObj. This also sets the local field on imgObj, but not the database object.

  4. Closes the input stream.

  5. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdImage object. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  6. Creates a new InputStream named inpStream. Calls getDataInStream( ) to get the media data from the application OrdImage object and stores it in inpStream.

  7. Reads 32300 bytes from the beginning (that is, at an offset of 0) of inpStream into the byte array tempBuffer. The integer numRead will be set to the total number of bytes read, or -1 if the end of the input stream has been reached. In this case, if loading is successful, numRead should be equal to 32300.

  8. Creates a new FileOutputStream object named outStream. This output stream will write data to a local file named streamexample.dat.

  9. Runs the operations in the while loop if numRead is not equal to -1. The program should enter this loop.

  10. Writes the number of bytes read into tempBuffer into outStream if numRead is less than 32300 (that is, if not all the data was read).

  11. Writes 32300 bytes into outStream if numRead is 32300.

  12. Attempts to read more data from the input stream into the byte array. If all data has been read successfully, then numRead will be set to -1 and the program will exit the loop. If there is still unread data in the input stream, then it will be read into the byte array and steps 10 and 11 will be repeated.

  13. Closes both the input stream and the output stream after exiting the while loop.

  14. Creates and executes a SQL statement that will update the database OrdImage object with the contents of imgObj. This update will set the attributes on the database object to match the application object.

  15. Handles any errors or exceptions raised by the code.

2.3.2.8 byteArrayBasedExample( ) Method

Example 2-27 shows a user-defined method named byteArrayBasedExample( ), which uses the loadDataFromByteArray( ) method to load media data into the application object.

Example 2-27 byteArrayBasedExample( ) Method (Image)

public void byteArrayBasedExample(OracleConnection con){
     try{
          int index = 0;
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery
               ("select * from ORDIMAGETAB where id = 4 for update ");
          while(rs.next( )){
               index = rs.getInt(1);
               OrdImage imgObj = (OrdImage) rs.getCustomDatum(2,
                    OrdImage.getFactory( ));
               [2] File ff = new File("imgdemo.dat");
               int fileLength = (int) ff.length( );
               byte[ ] data = new byte[fileLength];
               [3] FileInputStream fStream = new
                    FileInputStream("imgdemo.dat");
               [4] fStream.read(data,0,fileLength);
               [5] imgObj.loadDataFromByteArray(data);
               [6] fStream.close( );
               [7] imgObj.setProperties( );
               [8] byte[ ] resArr = imgObj.getDataInByteArray( );
               [9] System.out.println("byte array length : " + 
                    resArr.length);
               [10] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update ordimagetab set image = 
                    ? where id = " + index);
               stmt1.setCustomDatum(1,imgObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("successful");
     }
     [11] catch(Exception e){
          System.out.println("exception raised " + e);
     }
}

The byteArrayBasedExample( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdImage object named imgObj, and populates imgObj with media data through the same process described in steps 1 through 5 of Example 2-22. In this method, you will be operating on the contents of the row where id=4.

  2. Determines the size (in bytes) of the local file imgdemo.dat and creates a byte array of the same size.

  3. Creates a new FileInputStream object. This input stream contains the contents of imgdemo.dat.

  4. Reads the contents of the input stream into the byte array.

  5. Uses the loadDataFromByteArray( ) method to load the media data in the byte array into the database OrdImage object and into imgObj. This also sets the local field on imgObj, but not the database object.

  6. Closes the input stream.

  7. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdImage object. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  8. Uses the getDataInByteArray( ) method to get the media data from the application OrdImage object and load it into a local byte array named resArr.

  9. Gets the length of resArr and prints it to the screen to verify the success of the loading.

  10. Creates and executes a SQL statement that will update the database OrdImage object with the contents of imgObj. This update will set the attributes on the database object to match the application object.

  11. Handles any errors or exceptions raised by the code.

2.3.2.9 processExample( ) Method

Example 2-28 shows a user-defined method named processExample( ), which uses the process( ) and processCopy( ) methods to manipulate the media data in the application object.

Example 2-28 processExample( ) Method (Image)

public void processExample(OracleConnection con){
     try{
          int index1 = 0;
          [1] Statement s1 = con.createStatement( );
          OracleResultSet rs1 = (OracleResultSet)s1.executeQuery
               ("select * from ORDIMAGETAB where id = 2 for update ");
          while(rs1.next( )){
               index1 = rs1.getInt(1);
               OrdImage imgObj = (OrdImage) rs1.getCustomDatum(2,
                    OrdImage.getFactory( ));
               [2] OrdImage imgObj2 = (OrdImage) rs1.getCustomDatum(3,
                    OrdImage.getFactory( ));
               try{
                    [3] imgObj.processCopy("maxScale=32 32, fileFormat=
                         GIFF", imgObj2);
                    [4] imgObj.process("fileFormat=JFIF");
                    [5] System.out.println(getAllAttributesAsString
                         (imgObj));
                    [6] System.out.println(getAllAttributesAsString(imgObj2));
               }
               [7] catch (Exception e){
                    System.out.println("Exception raised in process"
                         + e );
               }
               [8] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update ordimagetab set image =
                    ?, image2 = ? where id = " + index1);
               stmt1.setCustomDatum(1,imgObj);
               stmt1.setCustomDatum(2,imgObj2);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs1.close( );
          s1.close( );
     }
     [9] catch(Exception e){
          System.out.println("Exception raised: " + e);
     }
     System.out.println("successful");
}

The processExample( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdImage object named imgObj, and populates imgObj with media data through the same process described in steps 1 through 5 of Example 2-22. In this method, you will be operating on the contents of the second column of the row where id=2. The database OrdImage object is named image.

  2. Creates a local OrdImage object named imgObj2. Populates imgObj2 with the contents of the OrdImage object in the third column of the current row in the OracleResultSet. This database OrdImage column is named image2.

  3. Populates the image data in imgObj2 with a 32 x 32 GIF thumbnail image generated from the image data in imgObj. imgObj is unchanged by this operation.

  4. Uses the process( ) method to convert the image in imgObj to a JPEG (JFIF) image.

  5. Gets the attributes of imgObj by using the getAllAttributesAsString( ) method, and prints the attributes to the screen. See Section 2.3.2.5 for more information on getAllAttributesAsString( ).

  6. Gets the attributes of imgObj2 by using the getAllAttributesAsString( ) method, and prints the attributes to the screen. See Section 2.3.2.5 for more information on getAllAttributesAsString( ).

  7. Handles any errors or exceptions raised by the code in steps 3 through 6.

  8. Creates and executes a SQL statement that will update the appropriate database OrdImage objects with the contents of imgObj and imgObj2.

  9. Handles any errors or exceptions raised by the code.

2.3.2.10 sigGeneration( ) Method

Example 2-29 shows a user-defined method named sigGeneration( ), which generates a signature for a given OrdImage object and stores it in the database.

Example 2-29 sigGeneration( ) Method (Image)

public void sigGeneration(OracleConnection con){
     byte[ ] ctx[ ] = new byte [4000][1];
     try{
          [1] int IMG_ID=10;
          int SIG_ID=11;
          int IMG_COL=2;
          int SIG_COL=2;
          [2] Statement get_image_obj = con.createStatement( );
          Statement get_sig_obj = con.createStatement( );
          [3] OracleResultSet get_image_obj_result = 
               (OracleResultSet)get_image_obj.executeQuery ("select * from
               ordimagetab where id =" + IMG_ID + " for update");
          OracleResultSet get_sig_result = (OracleResultSet)
               get_sig_obj.executeQuery("select * from sigtable where id =" +
               SIG_ID + " for update");
          [4] get_image_obj_result.next( );
          get_sig_result.next( );
          [5] OrdImage img_obj = (OrdImage)get_image_obj_result.getCustomDatum
               (IMG_COL, OrdImage.getFactory( ));
          [6] OrdImageSignature img_sig = (OrdImageSignature)
               get_sig_result.getCustomDatum(SIG_COL, 
               OrdImageSignature.getFactory( ));
          [7] img_obj.setProperties( ); 
          [8] img_obj.importData(ctx);
          [9] img_sig.generateSignature(img_obj);
          [10] OraclePreparedStatement update_sig = (OraclePreparedStatement)
               con.prepareCall("update sigtable set sig = ?
               where id =" + SIG_ID);
          update_sig.setCustomDatum(1,img_sig);
          update_sig.execute( );
          update_sig.close( ) ;
          [11] get_sig_result.close( );
          get_image_obj_result.close( );
          get_sig_obj.close( );
          get_image_obj.close( );
          System.out.println("image signature generation complete.");
     } 
     [12] catch(Exception e){
          System.out.println("exception raised " + e);
          System.out.println("image signature generation failed");
     } 
}

The code in sigGeneration( ) performs the following operations:

  1. Creates four integers that have the following values:

    • IMG_ID is the primary key of the OrdImage object in ORDIMAGETAB for which the signature will be generated.

    • SIG_ID is the primary key of the OrdImageSignature object in SIGTABLE where the signature will be stored.

    • IMG_COL is the column number of the OrdImage objects in ORDIMAGETAB.

    • SIG_COL is the column number of the OrdImageSignature objects in SIGTABLE.

  2. Creates two Statement objects.

  3. Executes the given SQL queries and puts the results in two local OracleResultSet objects. In this case, the SQL queries select the data in the following locations:

    • In ORDIMAGETAB, the database row where the primary key is 10.

    • In SIGTABLE, the database row where the primary key is 11.

  4. Advances to the proper row of the result sets.

  5. Creates a local OrdImage object named img_obj. Populates img_obj with the contents of the OrdImage object in the given column of the current row of the result set.

  6. Creates a local OrdImageSignature object named img_sig. Populates img_sig with the contents of the OrdImageSignature object in the given column of the current row of the result set.

  7. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdImage object. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  8. Imports data into the local OrdImage object.

  9. Generates a signature for img_obj and stores it in img_sig.

  10. Creates and executes a SQL statement that will update the database OrdImageSignature object with the contents of img_sig.

  11. Explicitly closes the OracleResultSet and Statement objects.

  12. Catches any exceptions or errors raised by the code.

2.3.2.11 imageMatchingScore( ) Method

Example 2-30 shows the imageMatchingScore( ) method, which generates signatures for two OrdImage objects and compares them based on different criteria.

Example 2-30 imageMatchingScore( ) Method (Image)

public void imageMatchingScore(OracleConnection con){ 
     byte[ ] ctx[ ] = new byte [4000][1];
     try {
          [1] int IMG_ID1=10;
          int SIG_ID1=10;
          int IMG_ID2=11;
          int SIG_ID2=11;
          int IMG_COL=2;
          int SIG_COL=2;
          [2] Statement get_image_obj = con.createStatement( );
          Statement get_sig_obj = con.createStatement( );
          [3] OracleResultSet get_image_obj_result1 = (OracleResultSet)
               get_image_obj.executeQuery("select * from ordimagetab
               where id ="+ IMG_ID1 +" for update");
          OracleResultSet get_sig_result1 = (OracleResultSet)
               get_sig_obj.executeQuery("select * from sigtable
               where id =" +SIG_ID1 + " for update");
          OracleResultSet get_image_obj_result2 = (OracleResultSet)
               get_image_obj.executeQuery("select * from ordimagetab
               where id ="+ IMG_ID2 +" for update");
          OracleResultSet get_sig_result2 = (OracleResultSet)
               get_sig_obj.executeQuery("select * from sigtable
               where id =" +SIG_ID2 + " for update");
          [4] get_image_obj_result1.next( );
          get_sig_result1.next( );
          get_image_obj_result2.next( );
          get_sig_result2.next( );
          [5] OrdImage img_obj1 = (OrdImage)
               get_image_obj_result1.getCustomDatum(IMG_COL,
               OrdImage.getFactory( ));
          [6] OrdImageSignature img_sig1 = (OrdImageSignature)
               get_sig_result1.getCustomDatum(
               SIG_COL,OrdImageSignature.getFactory( ));
          [7] img_obj1.setProperties( );
          [8] img_obj1.importData(ctx);
          [9] img_sig1.generateSignature(img_obj1);
          [10] OrdImage img_obj2 = (OrdImage)get_image_obj_result2.
               getCustomDatum(IMG_COL, OrdImage.getFactory( ));
          [11] OrdImageSignature img_sig2 = (OrdImageSignature)
               get_sig_result2.getCustomDatum(
               SIG_COL,OrdImageSignature.getFactory( ));
          [12] img_obj2.setProperties( );
          [13] img_obj2.importData(ctx);
          [14] img_sig2.generateSignature(img_obj2);
          [15] float gscore = OrdImageSignature.evaluateScore(img_sig1,
               img_sig2,"color=1", con);
          System.out.println("score value (global color comparison):" +
               gscore);
          [16] float lscore = OrdImageSignature.evaluateScore(img_sig1,
               img_sig2,"color=1 location=1", con);
          System.out.println("Score value (local color comparison):" + lscore);
          [17] get_sig_result2.close( );
          get_image_obj_result2.close( );
          get_sig_result1.close( );
          get_image_obj_result1.close( );
          get_sig_obj.close( );
          get_image_obj.close( );
     }
     [18] catch(Exception e){
          System.out.println("exception raised " + e);
          System.out.println("Image matching score computation failed");
     }
}

The code in the imageMatchingScore( ) method performs the following operations:

  1. Creates six integers that have the following values:

    • IMG_ID1 is the primary key of the OrdImage object in ORDIMAGETAB for which the first signature will be generated.

    • SIG_ID1 is the primary key of the OrdImageSignature object in SIGTABLE where the first signature will be stored.

    • IMG_ID2 is the primary key of the OrdImage object in ORDIMAGETAB for which the second signature will be generated.

    • SIG_ID2 is the primary key of the OrdImageSignature object in SIGTABLE where the second signature will be stored.

    • IMG_COL is the column number of the OrdImage objects in ORDIMAGETAB.

    • SIG_COL is the column number of the OrdImageSignature objects in SIGTABLE.

  2. Creates two Statement objects.

  3. Executes the given SQL queries and puts the results in four local OracleResultSet objects. In this case, the SQL queries select the data in the following locations:

    • In ORDIMAGETAB, the database row where the primary key is 10.

    • In SIGTABLE, the database row where the primary key is 10.

    • In ORDIMAGETAB, the database row where the primary key is 11.

    • In SIGTABLE, the database row where the primary key is 11.

  4. Advances to the proper row of the result sets.

  5. Creates a local OrdImage object named img_obj1. Populates img_obj1 with the contents of the OrdImage object in the second column of the row in ORDIMAGETAB where the primary key is 10.

  6. Creates a local OrdImageSignature object named img_sig1. Populates img_sig1 with the contents of the OrdImageSignature object in the second column of the row in SIGTABLE where the primary key is 10.

  7. Calls setProperties( ) to extract properties values from the media data and set them in img_obj1. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  8. Imports data into img_obj1.

  9. Generates a signature for img_obj1 and stores it in img_sig1.

  10. Creates a local OrdImage object named img_obj2. Populates img_obj2 with the contents of the OrdImage object in the second column of the row in ORDIMAGETAB where the primary key is 11.

  11. Creates a local OrdImageSignature object named img_sig2. Populates img_sig2 with the contents of the OrdImageSignature object in the second column of the row in SIGTABLE where the primary key is 11.

  12. Calls setProperties( ) to extract properties values from the media data and set them in img_obj2. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  13. Imports data into img_obj2.

  14. Generates a signature for img_obj2 and stores it in img_sig2.

  15. Compares the two image signatures based on the color attribute and print the newly generated score to the screen.

  16. Compares the two image signatures based on the color and location attributes and print the newly generated score to the screen.

  17. Explicitly closes the Statement and OracleResultSet objects.

  18. Handles any exceptions or errors that were generated by the method.

2.3.2.12 sigSimilarity( ) Method

Example 2-31 shows the sigSimilarity( ) method, which compares the image signatures of two objects and determines if they match.

Example 2-31 sigSimilarity( ) Method (Image)

public void sigSimilarity(OracleConnection con){
     byte[ ] ctx[ ] = new byte [4000][1];
     try {
          [1] int IMG_ID1=10;
          int SIG_ID1=10;
          int IMG_ID2=11;
          int SIG_ID2=11;
          int IMG_COL=2;
          int SIG_COL=2;
          [2] double similarity_threshold= 20.0;
          [3] Statement get_image_obj = con.createStatement( );
          Statement get_sig_obj = con.createStatement( );
          [4] OracleResultSet get_image_obj_result1 = (OracleResultSet)
               get_image_obj.executeQuery("select * from ordimagetab
               where id ="+ IMG_ID1 +" for update");
          OracleResultSet get_sig_result1 = (OracleResultSet)
               get_sig_obj.executeQuery("select * from sigtable
               where id =" +SIG_ID1 + " for update");
          OracleResultSet get_image_obj_result2 = (OracleResultSet)
               get_image_obj.executeQuery("select * from ordimagetab
               where id ="+ IMG_ID2 +" for update");
          OracleResultSet get_sig_result2 = (OracleResultSet)
               get_sig_obj.executeQuery("select * from sigtable
               where id =" +SIG_ID2 + " for update");
          [5] get_image_obj_result1.next( );
          get_sig_result1.next( );
          get_image_obj_result2.next( );
          get_sig_result2.next( );
          [6] OrdImage img_obj1 = (OrdImage)get_image_obj_result1.
               getCustomDatum(IMG_COL, OrdImage.getFactory( ));
          [7] OrdImageSignature img_sig1 = (OrdImageSignature)get_sig_result1.
               getCustomDatum(SIG_COL,OrdImageSignature.getFactory( ));
          [8] img_obj1.setProperties( );
          [9] img_obj1.importData(ctx);
          [10] img_sig1.generateSignature(img_obj1);
          [11] OrdImage img_obj2 = (OrdImage) get_image_obj_result2.
               getCustomDatum(IMG_COL, OrdImage.getFactory( ));
          [12] OrdImageSignature img_sig2 = (OrdImageSignature)get_sig_result2.
               getCustomDatum(SIG_COL,OrdImageSignature.getFactory( ));
          [13] img_obj2.setProperties( );
          [14] img_obj2.importData(ctx);
          [15] img_sig2.generateSignature(img_obj2);
          [16] int result = OrdImageSignature.isSimilar(img_sig1, img_sig2,
               "color=1 texture=1 shape=1 location=1",
               (float)similarity_threshold,con);
          if (result==1){
               System.out.println("Signatures are similar ");
          }
          else{
               System.out.println("Signatures are different ");
          }
          [17] get_sig_result2.close( );
          get_image_obj_result2.close( );
          get_sig_result1.close( );
          get_image_obj_result1.close( );
          get_sig_obj.close( );
          get_image_obj.close( );
     }
     [18] catch(Exception e){
          System.out.println("exception raised " + e);
          System.out.println("Signature similarity computation failed");
     }
}
  1. Creates six integers that have the following values:

    • IMG_ID1 is the primary key of the OrdImage object in ORDIMAGETAB for which the first signature will be generated.

    • SIG_ID1 is the primary key of the OrdImageSignature object in SIGTABLE where the first signature will be stored.

    • IMG_ID2 is the primary key of the OrdImage object in ORDIMAGETAB for which the second signature will be generated.

    • SIG_ID2 is the primary key of the OrdImageSignature object in SIGTABLE where the second signature will be stored.

    • IMG_COL is the column number of the OrdImage objects in ORDIMAGETAB.

    • SIG_COL is the column number of the OrdImageSignature objects in SIGTABLE.

  2. Sets the threshold score at which the images will be considered a match.

  3. Creates two Statement objects.

  4. Executes the given SQL queries and puts the results in four local OracleResultSet objects. In this case, the SQL queries select the data in the following locations:

    • In ORDIMAGETAB, the database row where the primary key is 10.

    • In SIGTABLE, the database row where the primary key is 10.

    • In ORDIMAGETAB, the database row where the primary key is 11.

    • In SIGTABLE, the database row where the primary key is 11.

  5. Advances to the proper row of the result sets.

  6. Creates a local OrdImage object named img_obj1. Populates img_obj1 with the contents of the OrdImage object in the second column of the row in ORDIMAGETAB where the primary key is 10.

  7. Creates a local OrdImageSignature object named img_sig1. Populates img_sig1 with the contents of the OrdImageSignature object in the second column of the row in SIGTABLE where the primary key is 10.

  8. Calls setProperties( ) to extract properties values from the media data and set them in img_obj1. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  9. Imports data into img_obj1.

  10. Generates a signature for img_obj1 and stores it in img_sig1.

  11. Creates a local OrdImage object named img_obj2. Populates img_obj2 with the contents of the OrdImage object in the second column of the row in ORDIMAGETAB where the primary key is 11.

  12. Creates a local OrdImageSignature object named img_sig2. Populates img_sig2 with the contents of the OrdImageSignature object in the second column of the row in SIGTABLE where the primary key is 11.

  13. Calls setProperties( ) to extract properties values from the media data and set them in img_obj2. See "setProperties( )" in Chapter 5 for a list of the properties values extracted and set.

  14. Imports data into img_obj2.

  15. Generates a signature for img_obj2 and stores it in img_sig2.

  16. Determines if the two image signatures match, based on the color, texture, shape, and location attributes. If the score is less than or equal to 20, the result is 1 and the appropriate message is printed to the screen. If not, the result is 0 and the appropriate message is printed to the screen.

  17. Explicitly closes the Statement and OracleResultSet objects.

  18. Handles any exceptions or errors that were generated by the method.

2.4 OrdVideo Example

The video example (including VideoExample.sql and VideoExample.java) contains user-defined methods that use SQL, JDBC, and interMedia Java Classes APIs to perform the following operations:

2.4.1 VideoExample.sql

Example 2-32 shows the contents of VideoExample.sql.

Example 2-32 Contents of VideoExample.sql

set echo on


--PLEASE change system password
connect system/manager
drop user VIDEOUSER cascade;
[1] create user VIDEOUSER identified by VIDEOUSER ;
grant connect,resource to VIDEOUSER identified by VIDEOUSER;


[2] connect VIDEOUSER/VIDEOUSER


[3] CREATE TABLE TVID(n NUMBER, vid ORDSYS.ORDVIDEO);


-- Note - the OrdVideo.init method was added in interMedia 8.1.7.
-- If you are running against an older release of interMedia and the
-- Oracle database, you will have to modify the following INSERT statements
-- to use the OrdVideo default constructor.


[4] INSERT INTO TVID VALUES(1, ORDSYS.ORDVideo.init( ));
INSERT INTO TVID VALUES(2, ORDSYS.ORDVideo.init( ));
INSERT INTO TVID VALUES(3, ORDSYS.ORDVideo.init( ));
commit;
/

The SQL statements in VideoExample.sql perform the following operations:

  1. Create a user named VIDEOUSER amd grant the appropriate permissions to the user.

  2. Connect to the database server as VIDEOUSER.

  3. Create a table named TVID with two columns: a column of numbers and a column of OrdVideo objects.

  4. Add three rows to the table, each containing an empty OrdVideo object.

See Oracle interMedia User's Guide and Reference for more information on the init method.

2.4.2 VideoExample.java

Section 2.4.2.1 through Section 2.4.2.8 show the methods contained in the VideoExample.java sample file.

2.4.2.1 main( ) Method

Example 2-33 shows the main( ) method.

Example 2-33 main( ) Method (Video)

public static void main (String args[ ]){
     byte[ ] ctx = new byte[4000];
     OracleConnection con = null;
     try {
          VideoExample tk = new VideoExample( );
          [1] con = tk.connect( );
          //Include the following line only if you are running
          //an Oracle 8.1.7 database or later.
          //If you are running a database server prior to 8.1.7,
          //the call will fail.
          [2] OrdMediaUtil.imCompatibilityInit(con);
          [3] tk.loadDataFromFile(con);
          tk.extractProperties(con);
          tk.printProperties(con);
          tk.loadDataFromStream(con);
          tk.otherMethods(con);
          tk.loadDataFromByteArray(con);
          [4] con.commit( );
          [5] con.close( );
          System.out.println("Done.");
     }
     [6] catch (Exception e) {
          try {
               System.out.println("Exception : " + e);
               con.close( );
          }
          catch(Exception ex) {
               System.out.println("Close Connection Exception : " + ex);
          }
     }
}

The code in the main( ) method performs the following operations:

  1. Uses the connect( ) method to make a connection to a database table.

  2. Ensures the compatibility of your application with later releases of the Oracle database. See Section 1.8 for more information.

  3. Calls several methods (also defined in VideoExample.java) that manipulate objects on the database server and the local machine.

  4. Commits any changes made to the database table.

  5. Closes the connection to the database.

  6. Handles any errors or exceptions raised by the code.

Section 2.4.2.2 through Section 2.4.2.8 will provide information on the methods called from the main( ) method in the order in which they are called, not in the order they appear in VideoExample.java.

2.4.2.2 connect( ) Method

Example 2-34 shows a user-defined method named connect( ), which makes a connection from the application to the database.

Example 2-34 connect( ) Method (Video)

public OracleConnection connect( ) throws Exception{
     String connectString;
     [1] Class.forName ("oracle.jdbc.driver.OracleDriver");
     [2] connectString = "jdbc:oracle:oci8:@";
     [3] OracleConnection con = (OracleConnection)
          DriverManager.getConnection(connectString,"VIDEOUSER","VIDEOUSER");
     [4] con.setAutoCommit(false);
     return con;
}

The connect( ) method performs the following operations:

  1. Loads the JDBC drivers directly, because the Oracle database uses a JDK-compliant Java virtual machine.

  2. Defines a string that contains the URL of the database to which you will connect. You may need to change this string to match your database.

  3. Sets the connection to the database, using the URL contained in connectString, the user name VIDEOUSER, and the password VIDEOUSER. The user name and password were created by VideoExample.sql.

  4. Disables the auto-commit mode. This means that you must commit or roll back manually with the commit( ) or rollback( ) methods, respectively.

2.4.2.3 loadDataFromFile( ) Method

Example 2-35 shows a user-defined method named loadDataFromFile( ), which uses the interMedia loadDataFromFile( ) method to load media data into the application object.

Example 2-35 loadDataFromFile( ) Method (Video)

public void loadDataFromFile(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          [2] OracleResultSet rs = (OracleResultSet)s.executeQuery
               ("select * from TVID where n = 1 for update ");
          int index = 0;
          [3] while(rs.next( )){
               [4] index = rs.getInt(1);
               [5] OrdVideo vidObj = (OrdVideo) rs.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [6] vidObj.loadDataFromFile("testvid.dat");
               [7] vidObj.getDataInFile("output1.dat");
               System.out.println("************AFTER getDataInFile ");
               [8] System.out.println("getContentLength output : " +
                    vidObj.getContentLength( ));
               [9] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tvid set vid = ? 
                    where n = " + index);
               stmt1.setCustomDatum(1,vidObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("loading successful");
     }
     [10] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("loading unsuccessful");
     }
}

The loadDataFromFile( ) method performs the following operations:

  1. Creates an OracleStatement object.

  2. Executes the given SQL query and puts the results into a local OracleResultSet object. In this case, the SQL query selects the data in the database row where n=1.

  3. Performs the operations in the loop while there are results in the OracleResultSet that have not been processed. However, in this case, there is only one row included in the OracleResultSet, so the operations in the loop will run once.

  4. Sets an index variable to the value of the integer in the first column of the first row in the OracleResultSet (in this case, the value is 1).

  5. Creates a local OrdVideo object named vidObj. Populates vidObj with the contents of the OrdVideo object in the second column of the current row in the OracleResultSet.

  6. Uses the loadDataFromFile( ) method to load the media data in testvid.dat into the database OrdVideo object and into vidObj. This also sets the local field on vidObj, but not the database object.

  7. Uses the getDataInFile( ) method to get the media data from the application OrdVideo object and load it into a file on the local system named output1.dat.

  8. Gets the content length of vidObj and prints it to the screen to verify the success of the loading.

  9. Creates and executes a SQL statement that will update the database OrdVideo object with the contents of vidObj. This update will set the local attribute on the database object to match the application object.

  10. Handles any errors or exceptions raised by the code.

2.4.2.4 extractProperties( ) Method

Example 2-36 shows a user-defined method named extractProperties( ), which sets the properties in the application object.

Example 2-36 extractProperties( ) Method (Video)

public void extractProperties(OracleConnection con){
     byte[ ] ctx[ ] = new byte [4000][1];
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery
               ("select * from TVID where n = 1 for update");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdVideo vidObj = (OrdVideo) rs.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [2] vidObj.setProperties(ctx);
               System.out.println("set Properties called");
               [3] if(vidObj.checkProperties(ctx)) {
                    System.out.println("checkProperties called");
                    System.out.println("setBindParams successful");
                    System.out.println("setProperties successful");
                    System.out.println("checkProperties successful");
                    System.out.println("extraction  successful");
               }
               else {
                    System.out.println("checkProperties called");
                    System.out.println("extraction not successful");
                    System.out.println("checkProperties successful");
               }
               [4] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tvid set vid = ? where 
                    n = " + index);
               stmt1.setCustomDatum(1,vidObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs.close( );
          s.close( );
     }
     [5] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("extract prop unsuccessful");
     }
}

The extractProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdVideo object named vidObj, and populates vidObj with media data through the same process described in steps 1 through 5 of Example 2-35. In this method, you will be operating on the contents of the row where n=1.

  2. Calls setProperties( ) to extract properties values from the media data and set them in the application OrdVideo object. See "setProperties(byte[ ][ ])" in Chapter 8 for a list of the properties values extracted and set.

  3. Calls checkProperties( ) to compare the properties values in the application object with the values in the media data. If all values are the same, checkProperties( ) returns true and the appropriate messages are printed to the screen. If any values differ, checkProperties( ) returns false and the appropriate messages are printed to the screen.

  4. Creates and executes a SQL statement that will update the database OrdVideo object with the contents of vidObj.

  5. Handles any errors or exceptions raised by the code.

2.4.2.5 printProperties( ) Method

Example 2-37 shows a user-defined method named printProperties( ), which prints the attributes of the application object to the screen.

Example 2-37 printProperties( ) Method (Video)

public void printProperties(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet)s.executeQuery
               ("select * from TVID where n = 1 ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdVideo vidObj = (OrdVideo) rs.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [2] System.out.println("format: " + vidObj.getFormat( ));
               System.out.println("mimetype: " + vidObj.getMimeType( ));
               System.out.println("width: " + vidObj.getWidth( ));
               System.out.println("height: " + vidObj.getHeight( ));
               System.out.println("frame resolution: " +
                    vidObj.getFrameResolution( ));
               System.out.println("frame rate: " + vidObj.getFrameRate( ));
               System.out.println("video duration: " + 
                    vidObj.getVideoDuration( ));
               System.out.println("number of frames: " +
                    vidObj.getNumberOfFrames( ));
               System.out.println("description : " +
                    vidObj.getDescription( ));
               System.out.println("compression type: " +
                    vidObj.getCompressionType( ));
               System.out.println("bit rate: " + vidObj.getBitRate( ));
               System.out.println("num of colors: " + 
                    vidObj.getNumberOfColors( ));
          }
     }
     [3] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("print proerties unsuccessful");
     }
}

The printProperties( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdVideo object named vidObj, and populates vidObj with media data through the same process described in steps 1 through 5 of Example 2-35. In this method, you will be operating on the contents of the row where n=1.

  2. Gets the values of the properties in vidObj and prints them to the screen.

  3. Handles any errors or exceptions raised by the code.

2.4.2.6 loadDataFromStream( ) Method

Example 2-38 shows a user-defined method named loadDataFromStream( ), which uses the interMedia loadDataFromInputStream( ) method to load media data into the application object.

Example 2-38 loadDataFromStream( ) Method (Video)

public void loadDataFromStream(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TVID where n = 2 for update ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdVideo vidObj = (OrdVideo) rs.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [2] FileInputStream  fStream  = new FileInputStream
                    ("testvid.dat");
               [3] vidObj.loadDataFromInputStream(fStream);
               [4] vidObj.getDataInFile("output2.dat");
               [5] fStream.close( );
               System.out.println("************AFTER getDataInFile ");
               [6] System.out.println("getContentLength output : " +
                    vidObj.getContentLength( ));
               [7] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tvid set vid = ? 
                    where n = " + index);
               stmt1.setCustomDatum(1,vidObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          System.out.println("load data from stream successful");
     }
     [8] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("load data from stream unsuccessful");
     }
}

The loadDataFromStream( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdVideo object named vidObj, and populates vidObj with media data through the same process described in steps 1 through 5 of Example 2-35. In this method, you will be operating on the contents of the row where n=2.

  2. Creates a new FileInputStream object. This input stream contains the contents of the local file testvid.dat.

  3. Uses the loadDataFromInputStream( ) method to load the media data in the input stream into the database OrdVideo object and into vidObj. This also sets the local field on vidObj, but not the database object.

  4. Uses the getDataInFile( ) method to get the media data from the application OrdVideo object and load it into a file on the local system named output2.dat.

  5. Closes the local input stream.

  6. Gets the content length of vidObj and prints it to the screen to verify the success of the loading.

  7. Creates and executes a SQL statement that will update the database OrdVideo object with the contents of vidObj. This update will set the attributes on the database object to match the application object.

  8. Handles any errors or exceptions raised by the code.

2.4.2.7 otherMethods( ) Method

Example 2-39 shows a user-defined method named otherMethods( ), which attempts to use the processSourceCommand( ) method.

Example 2-39 otherMethods( ) Method (Video)

public void otherMethods(OracleConnection con){
     byte[ ] ctx[ ] = {new byte[4000]};
     byte[ ] res[ ] = {new byte[20]};
     [1] int suc = 1;
     try {
          [2] Statement s1 = con.createStatement( );
          OracleResultSet rs1 = (OracleResultSet)
          s1.executeQuery("select * from TVID where n = 1 for 
               update ");
          int index1 = 0;
          while(rs1.next( )) {
               index1 = rs1.getInt(1);
               OrdVideo vidObj = (OrdVideo) rs1.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [3] try {
                    byte[ ] pSRes = vidObj.processSourceCommand(ctx, 
                         "", "", res);
                    suc = 0;
               }
               [4] catch (Exception e) { 
                    System.out.println("Expected Exception raised in 
                         processSourceCommand(...)" );
               }
               [5] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tvid set vid = ? where 
                         n = " + index1);
               stmt1.setCustomDatum(1,vidObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
          rs1.close( );
          s1.close( );
     }
     [6] catch(Exception e){
          System.out.println("Exception raised " );
     }
     [7] if(suc == 1)
          System.out.println("other methods successful");
     else
          System.out.println("other methods unsuccessful");
}

The otherMethods( ) method performs the following operations:

  1. Creates an integer that will be used to indicate the success or failure of the method and sets it initially to 1 (for success).

  2. Creates a statement, a local OracleResultSet, and a local OrdVideo object named vidObj, and populates vidObj with media data through the same process described in steps 1 through 5 of Example 2-35. In this method, you will be operating on the contents of the row where n=1.

  3. Tries to call processSourceCommand( ) with no value specified for the command to be called on the server side. This should raise an exception, which means the code following the processSourceCommand( ) call will not be run and the code in the catch loop will. If an exception is not raised, then the method has failed and the success indicator is set to 0 (for failure).

  4. Prints the expected exception that was raised in step 3.

  5. Creates and executes a SQL statement that will update the database OrdVideo object with the contents of vidObj.

  6. Handles any unexpected errors or exceptions raised by the code.

  7. Prints the appropriate message to the screen based on the success or failure of the method.

2.4.2.8 loadDataFromByteArray( ) Method

Example 2-40 shows a user-defined method named loadDataFromByteArray( ), which uses the interMedia loadDataFromByteArray( ) method to load media data into the application object.

Example 2-40 loadDataFromByteArray( ) Method (Video)

public void loadDataFromByteArray(OracleConnection con){
     try {
          [1] Statement s = con.createStatement( );
          OracleResultSet rs = (OracleResultSet) s.executeQuery
               ("select * from TVID where n = 3 for update ");
          int index = 0;
          while(rs.next( )){
               index = rs.getInt(1);
               OrdVideo vidObj = (OrdVideo) rs.getCustomDatum(2,
                    OrdVideo.getFactory( ));
               [2] File ff = new File("testvid.dat");
               int fileLength = (int) ff.length( );
               byte[ ] data = new byte[fileLength];
               [3] FileInputStream  fStream  = new
                    FileInputStream("testvid.dat");
               [4] fStream.read(data,0,fileLength);
               [5] vidObj.loadDataFromByteArray(data);
               [6] fStream.close( );
               [7] vidObj.getDataInFile("output3.dat");
               [8] byte[ ] resArr = vidObj.getDataInByteArray( );
               [9] System.out.println("byte array length : " + 
                    resArr.length);
               [10] FileOutputStream outStream = new FileOutputStream
                    ("output4.dat");
               [11] outStream.write(resArr);
               [12] outStream.close( );
               [13] InputStream inpStream = vidObj.getDataInStream( );
               int length = 32768;
               byte[ ] tempBuffer = new byte[32768];
               [14] int numRead = inpStream.read(tempBuffer,0,length);
               try {
                    [15] outStream = new FileOutputStream("output5.dat");
                    [16] while(numRead != -1) {
                         [17] if (numRead < 32768) {
                              length = numRead;
                              outStream.write(tempBuffer,0,length);
                              break;
                         }
                         [18] else
                              outStream.write(tempBuffer,0,length);
                         [19] numRead = inpStream.read(tempBuffer,0,length);
                    }
               }
               [20] finally {
                    outStream.close( );
                    inpStream.close( );
               }
               System.out.println("************AFTER getDataInFile ");
               [21] System.out.println(" getContentLength output : " + 
                    vidObj.getContentLength( ));
               [22] OraclePreparedStatement stmt1 = (OraclePreparedStatement)
                    con.prepareCall("update tvid set vid = ? where
                    n = " + index);
               stmt1.setCustomDatum(1,vidObj);
               stmt1.execute( );
               stmt1.close( ) ;
          }
     }
     [23] catch(Exception e) {
          System.out.println("exception raised " + e);
          System.out.println("loadData from byte array unsuccessful");
     }
}

The loadDataFromByteArray( ) method performs the following operations:

  1. Creates a statement, a local OracleResultSet, and a local OrdVideo object named vidObj, and populates vidObj with media data through the same process described in steps 1 through 5 of Example 2-35. In this method, you will be operating on the contents of the row where n=3.

  2. Determines the size (in bytes) of the local file testvid.dat and creates a byte array of the same size.

  3. Creates a new FileInputStream object. This input stream contains the contents of testvid.dat.

  4. Reads the contents of the input stream into the byte array.

  5. Uses the loadDataFromByteArray( ) method to load the media data in the byte array into the database OrdVideo object and into vidObj. This also sets the local field on vidObj, but not the database object.

  6. Closes the input stream.

  7. Uses the getDataInFile( ) method to get the media data from the application OrdVideo object and load it into a file on the local system named output3.dat.

  8. Uses the getDataInByteArray( ) method to get the media data from the application OrdVideo object and load it into a local byte array named resArr.

  9. Gets the length of resArr and prints it to the screen to verify the success of the loading.

  10. Creates a new FileOutputStream object named outStream. This output stream will write data to a local file named output4.dat.

  11. Writes the contents of resArr to output4.dat.

  12. Closes the output stream.

  13. Creates a new input stream named inpStream. Uses the getDataInStream( ) method to get the media data from the application OrdVideo object and store it in inpStream.

  14. Reads 32768 bytes from the beginning (that is, at an offset of 0) of inpStream into the byte array tempBuffer. The integer numRead will be set to the total number of bytes read, or -1 if the end of the input stream has been reached. In this case, if loading is successful, numRead should be equal to 32768.

  15. Re-opens OutStream. In this case, it will write data to a local file named output5.dat.

  16. Runs the operations in the while loop if numRead is not equal to -1. The program should enter this loop.

  17. Writes the number of bytes read into tempBuffer into outStream if numRead is less than 32768 (that is, if all the data was read).

  18. If numRead is 32768, writes 32768 bytes into outStream.

  19. Attempts to read more data from the input stream into the byte array. If all data has been read, then numRead will be set to -1 and the program will exit the loop. If there is still unread data in the input stream, then it will be read into the byte array and steps 17 and 18 will be repeated.

  20. Closes both the input stream and the output stream after exiting the while loop.

  21. Gets the content length of vidObj and prints it to the screen to verify the success of the loading.

  22. Creates and executes a SQL statement that will update the database OrdVideo object with the contents of vidObj. This update will set the attributes on the database object to match the application object.

  23. Handles any errors or exceptions raised by the code.




Previous Next
Oracle Logo
Copyright © 1999, 2002 Oracle Corporation

All rights reserved
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback