Skip Headers
Oracle® interMedia User's Guide
10g Release 2 (10.2)

Part Number B14302-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Master Index
Master Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

2 Application Development

You can develop traditional client/server or two-tier applications, or you can develop multitier applications. Either method can then deploy Web applications to run on an application server tier, be tightly integrated with Oracle Database, and allow users access to the application from their desktop through a Web browser.

Using a complete development framework supported by class library interfaces, you can create production quality Oracle interMedia ("interMedia") applications for use in a production environment where users can interact with the application through either the standalone client interface or a Web browser. For Web applications, which are based on standards such as TCP/IP, HTTP, HTML, XML, and XHTML, this is all facilitated by rapid developments in the underlying technology. As key software components become more tightly integrated, developers' tasks to design, create, and manage Web applications become faster, easier, and simpler to implement.

Using either the object type interface or the relational interface, interMedia provides Internet support for Oracle Application Server and Oracle Database and authoring tools so you can quickly develop Web-based applications to upload to the database, retrieve from it, and manipulate multimedia data for delivery to Web browsers.

Oracle interMedia supports application development by:

Section 2.2 describes how to use PL/SQL Gateway and PL/SQL Web Toolkit to develop PL/SQL Web applications. Section 2.3 describes how to use Java and JDBC to develop media-rich Java client applications based on Oracle interMedia Java Classes. Section 2.4 describes how to develop Java-based Web applications based on Oracle interMedia Java Classes and Oracle interMedia Java Classes for Servlets and JSP.

Chapter 3 describes a sample Web application, interMedia Photo Album, which is implemented using the following different technologies: PL/SQL, Java servlets and JavaServer Pages (JSP), and Microsoft Active Server Pages (ASP)/Visual Basic (VB). This sample application demonstrates how to apply the steps described in Section 2.2 and Section 2.4 in a real Web application to upload and retrieve media data stored in a database. Chapter 3 also describes an interMedia Code Wizard application that lets you create PL/SQL stored procedures for the PL/SQL Gateway to upload and retrieve media data stored in a database using interMedia object types.

Chapter 4 describes a sample Java application, IMExample, which is implemented using Java, JDBC, and Oracle interMedia Java Classes. This sample application demonstrates how to apply the steps described in Section 2.3 in a real Java application to upload and retrieve media data stored in a database.

2.1 Developing PL/SQL Client Applications Using the PL/SQL API

PL/SQL is a completely portable, high-performance transaction processing language that combines the data manipulation power of SQL with the data processing power of procedural languages.

This section briefly describes how to manipulate interMedia database objects with the PL/SQL Application Programming Interface (API). The following interMedia object types are available for storing media in the database:

Section 2.1.1 describes how to set up the environment to use Oracle interMedia with PL/SQL. Section 2.1.2 describes how to use standard SQL queries with interMedia objects. Section 2.1.3 describes how to retrieve media data from interMedia objects in a PL/SQL application. Section 2.1.4 describes how to upload media data into interMedia database objects in a PL/SQL application. Section 2.1.5 describes how to handle exceptions in a PL/SQL application.

All the examples in this section use the sample schemas, which are installed by default when you install Oracle. Refer to Oracle Database Sample Schemas for information about how these schemas were created and how you can use them yourself.

See Oracle interMedia Reference for details about the interMedia object types and available methods in the PL/SQL API.

2.1.1 Setting Up Your Environment for PL/SQL

To access files with PL/SQL, you must create a directory object in the database that points to a directory that is accessible by the database server. For example, the following command creates the MEDIA_DIR directory in the sample schema:

CREATE DIRECTORY MEDIA_DIR AS
    'c:\oracle\product\10.2.0\db_1\demo\schema\product_media';

To retrieve media data from the database to a file, you must grant the write permission on the specified directory to the appropriate user. For example:

GRANT WRITE ON DIRECTORY MEDIA_DIR TO SCOTT;

To upload media data from a file to the database, you must grant the read permission on the specified directory to the appropriate user. For example:

GRANT READ ON DIRECTORY MEDIA_DIR TO SCOTT;

2.1.2 Media Query in PL/SQL

You can include media attributes (for example: height, width, and MIME type) in standard SQL queries by using accessor methods (for example: getHeight, getWidth, and getMimeType). Example 2-1, Example 2-2, and Example 2-3 show how to use these accessor methods to query one or more object attributes for image, audio, and video objects, respectively.

Example 2-1 Image Query (Height, Width, and MimeType Attributes)

SELECT t.product_id                  id,
       t.product_photo.getHeight()   height,
       t.product_photo.getWidth()    width,
       t.product_photo.getMimeType() mimetype
  FROM pm.online_media t;

Example 2-2 Audio Query (MimeType Attribute)

SELECT t.product_id                  id,
       t.product_audio.getMimeType() mimetype
  FROM pm.online_media t;

Example 2-3 Video Query (MimeType Attribute)

SELECT t.product_id                  id,
       t.product_video.getMimeType() mimetype
  FROM pm.online_media t;

2.1.3 Media Download in PL/SQL

To download media from the database into a file on the file system, call the export method of the interMedia object. The following code example exports the image in the row with product_id 3117 to a file named 3117.jpg in the directory MEDIA_DIR. This code example highlights in bold the PL/SQL statements where this export operation takes place.

DECLARE
  img ORDImage;
  ctx RAW(64) := NULL;
BEGIN
  SELECT  product_photo 
    INTO  img 
    FROM  pm.online_media
    WHERE product_id = 3117;
  img.export(ctx, 'FILE', 'MEDIA_DIR', '3117.jpg');
END;
/

2.1.4 Media Upload in PL/SQL

Media upload means importing media data from the file system into the database tablespaces. The following series of steps is typical:

  1. Insert a new row into the table, creating new objects by using the init method of the interMedia object type.

  2. Call the import method of the interMedia object to bring the data from the file system into the database.

  3. Call the setProperties method of the interMedia object to determine and populate the attributes of the object.

  4. Update the table so that the interMedia object in the table contains the attribute values extracted in the previous step.

The PL/SQL code that implements these steps for inserting a new row in the PM.ONLINE_MEDIA table is shown in the following example:

DECLARE
  img ORDImage;
  aud ORDAudio;
  vid ORDVideo;
  ctx RAW(64) := NULL;
BEGIN
  -- Insert a new row into the pm.online_media table
  DELETE FROM pm.online_media WHERE product_id = 3003;
  INSERT INTO pm.online_media 
         (product_id, 
          product_photo, 
          product_audio,
          product_video)
  VALUES (3003, 
          ORDImage.init('FILE', 'MEDIA_DIR', 'laptop.jpg'),
          ORDAudio.init('FILE', 'MEDIA_DIR', 'laptop.mpa'),
          ORDVideo.init('FILE', 'MEDIA_DIR', 'laptop.rm'))
  RETURNING product_photo, product_audio, product_video
  INTO img, aud, vid;
  
  -- Bring the media into the database and populate the attributes  
  img.import(ctx); 
  -- ORDImage.import also calls ORDImage.setProperties;
  
  aud.import(ctx);
  aud.setProperties(ctx);
 
  vid.import(ctx);
  vid.setProperties(ctx);
    
  -- update the table with the properties we have extracted
  UPDATE pm.online_media
  SET    product_photo = img,
         product_audio = aud,
         product_video = vid
  WHERE  product_id = 3003;
  
  COMMIT;
END;
/

2.1.5 Handling interMedia Exceptions in PL/SQL

Possible errors that can occur during run time should always be handled in your application. This practice enables the program to continue its operation even when it encounters a run-time error. This practice also enables users to know what went wrong during program operation. Proper error handling practices ensure that, whenever possible, you will always be able to recover from an error while running an application. In addition, proper error handling provides you with the information you need so that you will always know what went wrong.

This section demonstrates proper error handling practices through the use of code examples. These examples show how to handle some common interMedia errors as well as other types of errors in PL/SQL programs. These examples are extracted from the sample applications described in Chapter 3. See Oracle interMedia Reference for more examples.

When handling exceptions, PL/SQL uses exception blocks. For example, in PL/SQL, the exception may appear as:

BEGIN
<some program logic>
EXCEPTION
     WHEN OTHERS THEN
     <some exception logic
END;

When you design, code, and debug your application, you are aware of the places in your program where processing might stop due to a failure to anticipate an error. Those are the places in your program where you must add exception handling blocks to handle the potential errors. For more information about handling PL/SQL exceptions, see Oracle Database PL/SQL User's Guide and Reference.

The following examples describe exception handling in the interMedia PL/SQL Web Toolkit Photo Album sample application.

2.1.5.1 Handling the Setting of Properties for Unknown Image Formats

If your program tries to set the properties of an uploaded image (it reads the image data to get the values of the object attributes so it can store them in the appropriate attribute fields) and the image format is not recognized, then the setProperties( ) method will fail. To catch this exception and work around this potential problem, the application uses the following exception block:

BEGIN
   new_image.setProperties();
EXCEPTION
   WHEN OTHERS THEN
         new_image.contentLength := upload_size;
         new_image.mimeType := upload_mime_type;
END;

In this example, this exception handler sets the MIME type and length of the image based on the values from the upload table described at the beginning of the insert_new_photo procedure. The browser sets a MIME type header when the file is uploaded. The application reads this header to set the ORDImage field.

2.1.5.2 Handling Image Processing for Unknown Image Formats

If your program tries to process an image in cases when the image format is unknown, then the processCopy( ) method will always fail. To work around this potential problem, the application uses the following exception block:

BEGIN
   new_image.processCopy( 'maxScale=50,50', new_thumb);
EXCEPTION
   WHEN OTHERS THEN
      new_thumb.deleteContent();
      new_thumb.contentLength := 0;
END;

In this example from the interMedia PL/SQL Web Toolkit Photo Album application, when the image format is unknown and a thumbnail image cannot be created, this exception handler deletes the content of the thumbnail image and sets its length to zero.

2.2 Developing PL/SQL Web Applications

SQL developers who are familiar with the database can develop Web applications that exclusively use Oracle Application Server and Oracle Database using the PL/SQL development environment. With the PL/SQL development environment, developers can come quickly up to speed to develop PL/SQL-based Web applications.

Developing Web applications using PL/SQL consists of developing one or more PL/SQL packages consisting of sets of stored procedures that interact with Web browsers through HTTP. Stored procedures can be executed in several ways:

Information in the stored procedure, such as tagged HTML text, is displayed in the Web browser as a Web page. These dynamic Web pages are generated by the database and are based on the database contents and the input parameters passed in to the stored procedure. Using PL/SQL stored procedures is especially efficient and powerful for generating dynamic Web page content.

There are two ways of generating HTML output from PL/SQL:

Use interMedia when media data such as images, audio, video, or combinations of all three are to be uploaded into and retrieved from database tables using the interMedia object types and their respective sets of methods.

Media upload procedures first perform a SQL INSERT operation to insert a row of data in the media table, which also initializes instances of the respective interMedia object columns with an empty BLOB. Next, a SQL SELECT FOR UPDATE operation selects the object columns for update. Finally, a SQL UPDATE operation updates the media objects in their respective columns. interMedia methods are called to do the following:

Media retrieval operations involve the following tasks:

interMedia methods are called to get the time that the media object was last updated, to determine if the media is stored locally in the database, in a BFILE, or at a URL location, to get the MIME type of the media object, and finally to retrieve the media data.

2.2.1 Using the PL/SQL Gateway and PL/SQL Web Toolkit

Oracle Application Server and Oracle Database install Oracle HTTP Server powered by the Apache HTTP server that contains the PL/SQL Gateway to communicate directly with a client Web browser.

Oracle HTTP Server serves mainly the static HTML files, images, and so forth, that a Web application uses, and is usually located in the file system where Oracle HTTP Server is installed. Oracle HTTP Server contains modules or plug-ins that extend its functions. One of these modules supplied by Oracle is the mod_plsql module, also known as the PL/SQL Gateway. The PL/SQL Gateway serves data dynamically from the database to Web browsers by calling PL/SQL stored procedures. The PL/SQL Gateway receives requests from a Web browser in the form of PL/SQL servlets or PL/SQL server pages that are mapped to PL/SQL stored procedure calls. PL/SQL stored procedures retrieve data from the database and generate an HTTP response containing the data and code from the PL/SQL Web Toolkit to display the generated Web page in a Web browser. The PL/SQL Web Toolkit contains a set of packages called htp, htf, and owa packages that can be used in the stored procedures to get information about the request, construct HTML tags, and return header information to the client Web browser.

Figure 2-1 shows these main components of the PL/SQL development environment, Oracle HTTP Server (a component of Oracle Application Server and Oracle Database), the Web browser, and the database. The following information describes how a client Web browser request is turned into a Web page response from the execution of the PL/SQL procedure:

  1. A client Web browser sends a PL/SQL server page or servlet request to Oracle HTTP Server.

  2. Oracle HTTP Server routes the request to the PL/SQL Gateway (mod_plsql).

  3. The PL/SQL Gateway forwards the request to the database using configuration information stored in the database access descriptor (DAD) and connects to the database.

  4. The PL/SQL Gateway prepares the call parameters and invokes the PL/SQL package and the PL/SQL stored procedure in the application.

  5. The PL/SQL procedure generates an HTML page using data from the database and special packages in the PL/SQL Web Toolkit accessed from the database. The PL/SQL Web Toolkit contains a set of packages called htp, htf, and owa packages that are used in the stored procedures to get information about the request, construct HTML tags, and return header information back to the client Web browser as the response returned to the PL/SQL Gateway.

  6. The PL/SQL Gateway sends the response to Oracle HTTP Server.

  7. Oracle HTTP Server sends the response to the client Web browser for display as a formatted Web page.

Figure 2-1 Components of the PL/SQL Development Environment

Description of modplsql.gif follows
Description of the illustration modplsql.gif

Usually, the returned formatted Web page has one or more additional links, and each link, when selected, sends another request to the database through the PL/SQL Gateway to execute one or more stored procedures. The generated response displays data on the client Web page usually with additional links, which, when selected, execute more stored procedures that return the generated response for display as yet another formatted Web page, and so forth. This is how the PL/SQL application in the PL/SQL development environment is designed to work.

Web application developers who use the PL/SQL development environment, create a PL/SQL package specification and body that describe procedures and functions that comprise the application. The package specification defines the procedures and functions used by the application, and the package body is the implementation of each procedure and function. All packages are compiled and stored in the database to perform specific operations for accessing data in the database and formatting HTML output for Web page presentation. To invoke these stored PL/SQL procedures, Web application developers use the request/response PL/SQL servlets and PL/SQL server pages (PSP) to allow Web browser clients to send requests and get back responses using HTTP.

Oracle HTTP Server maps a URL entered in a browser to a specific PL/SQL procedure stored in the database. It does this by storing specific configuration information by means of a DAD for each stored procedure. Thus, each DAD contains the database connection information that is needed by the Web server to translate the URL entered into a database connection in order to call the stored procedure.

Oracle HTTP Server listens for a request, routes the request to the PL/SQL Gateway, which forwards it to the database. Configuration information values stored in a DAD determine the database alias to use, the connection string to use for remote access, the procedure to use for uploading or downloading documents, and the user name and password information to allow access to the database. From the Web browser, the user specifies the URL that invokes the PL/SQL Gateway. The URL has a defined format specifying all required and optional parameters needed, including the location of the DAD and the name of the PL/SQL stored procedure to run, as shown in Example 2-4.

Example 2-4 URL Format Required for Invoking mod_plsql in a Web Browser

protocol://hostname[:port number]/DAD-name/[[!][schema name.][package name.]procedure_name[?query_string]]

For a detailed description of each parameter and options available, see Oracle Application Server mod_plsql User's Guide. However, to use the photo album application for interMedia and the PL/SQL Web Toolkit described in Section 3.1 in Chapter 3, the URL can be simplified to the format shown in Example 2-5.

Example 2-5 URL Format Required to Invoke mod_plsql in a Web Browser for the Photo Album Application

protocol://<hostname>[:<port-number>]/DAD-name/]procedure_name

When the URL is entered in the Web browser, it includes the protocol (HTTP or HTTPS), the name of the hosting Web server, and the port number to which it is listening to handle requests. Next, the specified virtual path includes /pls/<DAD-name> to indicate that the Web server is configured to invoke mod_plsql, and the location of the DAD on the Web server.

In Example 2-4, the last five parameters include the exclamation point (!) character, schema name, package name, procedure name, and query string. From the syntax, the exclamation point, schema name, package name, and query string parameters are optional; only the procedure name is required.

The exclamation point indicates that flexible parameter passing is being used. The schema name, if omitted, is resolved based on the user name. The package name, if omitted, means the procedure is standalone. The query string parameters are for the stored procedure and follow a special format. Of these five parameters, the procedure name must be specified in both the DAD and the URL. The other four parameters are specified in either the DAD or the URL, or not at all, depending on the application.

The URL displays the home page for the specified DAD. When the URL is entered in the address field of the Web browser page, it invokes either the specified DAD location only, or the specified DAD location along with the procedure name, or the specified DAD location along with the schema.package.procedure name. The response is returned as an HTML page. The HTML page contains the requested data and any other specified code for display in the client's Web browser. The Code Wizard described in Section 3.3.1 in Chapter 3 illustrates how this works. For example, to invoke the Code Wizard administration URL, enter the following URL shown in Step 3 in Section 3.3.2 in that chapter:

http://<hostname>:<port-number>/pls/ordcwadmin

The virtual path includes pls to indicate that the Web server is configured to invoke mod_plsql, followed by the name of the DAD used for the Code Wizard administrator, ordcwadmin.

When the HTML page is displayed, it resolves to the following URL for the Code Wizard administrator:

http://<hostname>:<port-number>/pls/ordcwadmin/ORDCWPKG.menu

ORDCWPKG.menu represents the package.procedure name, which is specified as the default home page in the ordcwadmin DAD.

When the PL/SQL Gateway is invoked, it uses the stateless model and does not allow a transaction to span across multiple HTTP requests. In this stateless model, applications typically can create a session to maintain state by using one of the following techniques: HTTP cookies, a hidden HTML field as an HTML form element of the HTML Form package, or storage of vital information in database tables for query. For more information, see Oracle Database Application Developer's Guide - Fundamentals.

2.3 Developing Java Client Applications Using JDBC

Developers who are familiar with Java and Java database connectivity (JDBC) can write media-rich Java applications using Oracle interMedia Java Classes. The classes in Oracle interMedia Java Classes are the Java proxy classes for interMedia database objects. These Java classes provide access to interMedia database objects through JDBC in a Java application.

The Java classes in Oracle interMedia Java Classes are included in the oracle.ord.im.* package. The Java classes are named similarly to the interMedia database objects, and in compliance with the standard Java naming convention:

Section 2.3.1 describes how to set up the environment to use Oracle interMedia Java Classes. Section 2.3.2 describes how to retrieve media data from interMedia objects in a Java application. Section 2.3.3 describes how to upload media data into interMedia database objects in a Java application. Section 2.3.4 describes how to handle exceptions in a Java application.

All the examples in this section use the sample schemas, which are installed by default when you install Oracle. Refer to Oracle Database Sample Schemas for information about how these schemas were created and how you can use them yourself.

See Oracle interMedia Java Classes API Reference for details about the available methods in these classes.

2.3.1 Setting Up Your Environment for Java

Before you can begin using interMedia Java Classes, you must set up your environment with the appropriate Java libraries and import the necessary Java classes. Follow these steps:

  1. Ensure that the following items are in your CLASSPATH environment variable:

    • Oracle JDBC drivers:

      <ORACLE_HOME>/jdbc/lib/ojdbc14.jar (preferred)

      <ORACLE_HOME>/jdbc/lib/classes12.jar (deprecated)

    • SQLJ run-time library:

      <ORACLE_HOME>/sqlj/lib/runtime12.jar

    • XDB Java library:

      <ORACLE_HOME>/rdbms/jlib/xdb.jar

    • Oracle interMedia Java Client library:

      <ORACLE_HOME>/ord/jlib/ordim.jar

  2. Add one or more of the following import statements to the Java program:

    Along with the standard JDBC classes included in the java.sql package, you must also import the Oracle JDBC extension class oracle.jdbc.OracleResultSet, as follows:

    import oracle.jdbc.OracleResultSet;
    
    

    Based on the type of media to be handled in the Java application, you might also need to add one or more of following import statements:

    import oracle.ord.im.OrdAudio;
    import oracle.ord.im.OrdDoc;
    import oracle.ord.im.OrdImage;
    import oracle.ord.im.OrdVideo;
    

2.3.2 Media Retrieval in Java

interMedia objects can be retrieved into Java applications as Java proxy objects to the interMedia database objects with the same names: OrdAudio, OrdDoc, OrdImage, and OrdVideo. After the JDBC connection is established, follow these steps to retrieve interMedia Java objects:

  1. Create the JDBC statement to select interMedia objects from the database:

    String query = "select product_photo, product_audio,"+
      " product_video, product_testimonials from" +   
      " pm.online_media where product_id=3117";
    PreparedStatement pstmt = conn.prepareStatement(query);
    
    
  2. Execute the query and obtain the result set:

    OracleResultSet rset = (OracleResultSet)pstmt.executeQuery();
    
    
  3. Retrieve the interMedia Java object from the result set:

    if ( rset.next() )
    {
    
      OrdImage imgProxy = (OrdImage)rset.getORAData(
              "product_photo", OrdImage.getORADataFactory());
      OrdAudio audProxy = (OrdAudio)rset.getORAData(
              "product_audio", OrdAudio.getORADataFactory());
      OrdVideo vidProxy = (OrdVideo)rset.getORAData(
              "product_video", OrdVideo.getORADataFactory());
      OrdDoc docProxy = (OrdDoc)rset.getORAData(
              "product_testimonials",
              OrdDoc.getORADataFactory());
    }
    

    Note:

    In Oracle interMedia release 8i and release 9i, the getCustomDatum method is used to retrieve the interMedia Java objects. In Oracle JDBC release 10g, the getCustomDatum method was deprecated and replaced by the getORAData method.

    In your Java program environment, be sure to use the same version for both the Oracle interMedia Java Client library (ordim.jar) and the Oracle JDBC library.

  4. Retrieve the media attributes. Media attributes can be retrieved directly from interMedia Java objects. For example:

    int height = imgProxy.getHeight();
    int width = imgProxy.getWidth();
    String audFormat = audProxy.getFormat();
    String vidMimetype = vidProxy.getMimeType();
    

2.3.3 Media Upload in Java

Follow these steps to upload media data into interMedia database objects in a Java application:

  1. Enter the following statement to enable the JDBC connection object to set the autocommit flag to false:

    conn.setAutoCommit(false);
    
    
  2. Retrieve interMedia Java objects from the database for updating. You can load media data into existing interMedia objects in a table or into nonexisting interMedia objects by creating a new row in a table.

    The following example includes a query you can use to load media data into existing interMedia objects in a table.

    //"for update" is required in the query string 
    //since we will update the row later.
    String query1 = "select product_photo," +
    " product_audio, product_video," +         
    " product_testimonials from" + 
    " pm.online_media where product_id=3106" +
    " for update";
     
    PreparedStatement pstmt = conn.prepareStatement(query1);
     
    OracleResultSet rset = (OracleResultSet)pstmt.executeQuery();
    
    if ( rset.next() )
    {
     
      OrdImage imgProxy = (OrdImage)rset.getORAData(
              "product_photo", OrdImage.getORADataFactory());
      OrdAudio audProxy = (OrdAudio)rset.getORAData( 
              "product_audio", OrdAudio.getORADataFactory());
      OrdVideo vidProxy = (OrdVideo)rset.getORAData( 
              "product_video", OrdVideo.getORADataFactory());
      OrdDoc docProxy = (OrdDoc)rset.getORAData( 
              "product_testimonials",
              OrdDoc.getORADataFactory());
    }
     
    rset.close();
    pstmt.close();
    
    

    The following example includes a query you can use to load media data into nonexisting interMedia objects by creating a new row.

    Note:

    This code segment assumes that there is no row with product_id=3106 in the pm.online_media table.
    String query2 = 
      "begin insert into pm.online_media " +
      " (product_id, product_photo, product_audio," +
      " product_video, product_testimonials) values" +
      " (3106, ordimage.init()," +
      " ordaudio.init(), ordvideo.init()," +
      " orddoc.init()) returning product_photo," +    
      " product_audio, product_video," +   
      " product_testimonials into ?, ?, ?, ?;end;";
     
    OracleCallableStatement cstmt =
     (OracleCallableStatement) conn.prepareCall(query2);
    cstmt.registerOutParameter(1, OrdImage._SQL_TYPECODE,
                                   OrdImage._SQL_NAME);
    cstmt.registerOutParameter(2, OrdAudio._SQL_TYPECODE,
                                   OrdAudio._SQL_NAME);
    cstmt.registerOutParameter(3, OrdVideo._SQL_TYPECODE,
                                   OrdVideo._SQL_NAME);
    cstmt.registerOutParameter(4, OrdDoc._SQL_TYPECODE,
                                   OrdDoc._SQL_NAME);
     
    cstmt.execute();
     
    OrdImage imgProxy = (OrdImage)cstmt.getORAData(1,
                         OrdImage.getORADataFactory());
    OrdAudio audProxy = (OrdAudio)cstmt.getORAData(2, 
                         OrdAudio.getORADataFactory());
    OrdVideo vidProxy = (OrdVideo)cstmt.getORAData(3, 
                         OrdVideo.getORADataFactory());
    OrdDoc docProxy = (OrdDoc)cstmt.getORAData(4, 
                         OrdDoc.getORADataFactory());
     
    cstmt.close();
    
    
  3. Load the media data from a file to the interMedia Java objects by calling the loadDataFromFile method:

    String imageFileName = "laptop.jpg";
    String audioFileName = "laptop.mpa";
    String videoFileName = "laptop.rm";
    String docFileName = "laptop.jpg";
    imgProxy.loadDataFromFile(imageFileName);
    audProxy.loadDataFromFile(audioFileName);
    vidProxy.loadDataFromFile(videoFileName);
    docProxy.loadDataFromFile(docFileName);
    
    
  4. Set the properties of the interMedia objects by populating the Java object fields with media attributes (optional):

    imgProxy.setProperties();
    audProxy.setProperties(new byte[1][64]);
    vidProxy.setProperties(new byte[1][64]);
    docProxy.setProperties(new byte[1][64], true);
    

    Note:

    The setProperties method will try to recognize the format of the media and populate the objects field with media information such as image height, image width, format, MIME type, and so on. If the media format is not recognized, the java.sql.SQLException error will be thrown.
  5. Update the database table with interMedia Java objects that have data already loaded:

    String query3 = "update pm.online_media set" +
        " product_photo=?, product_audio=?," + 
        " product_video=?, product_testimonials=?" +
        " where product_id=3106";
        OraclePreparedStatement pstmt = 
     (OraclePreparedStatement)conn.prepareStatement(query3);
        pstmt.setORAData(1, imgProxy);
        pstmt.setORAData(2, audProxy);
        pstmt.setORAData(3, vidProxy);
        pstmt.setORAData(4, docProxy);
     
        pstmt.execute();
        pstmt.close();
    
    
  6. Commit the transaction:

    conn.commit();
    

2.3.4 Handling interMedia Exceptions in Java

Possible errors that can occur during run time should always be handled in your application. This practice enables the program to continue its operation even when it encounters a run-time error. This practice also enables users to know what went wrong during program operation. Proper error handling practices ensure that, whenever possible, you will always be able to recover from an error while running an application. In addition, proper error handling provides you with the information you need so that you will always know what went wrong.

This section demonstrates proper error handling practices through the use of code examples. These examples show how to handle some common interMedia errors as well as other types of errors in Java programs. These examples are extracted from the sample applications described in Chapter 3 and Chapter 4. See Oracle interMedia Reference for more examples.

When handling exceptions, Java uses the try/catch block. For example, in Java, the exception may appear as:

try {
    //<some program logic>)
}
catch (exceptionName a) {
//Exception logic
}
finally {
//Execute logic if try block is executed even if an exception is caught
}

When you design, code, and debug your application, you are aware of the places in your program where processing might stop due to a failure to anticipate an error. Those are the places in your program where you must add exception handling blocks to handle the potential errors. For more information about handling Java exceptions, see Oracle Database Java Developer's Guide and Oracle Database JDBC Developer's Guide and Reference.

The following examples describe exception handling using the try/catch block. These examples are in either the interMedia IMExample application or are in the interMedia Java Servlet Photo Album application, the interMedia JavaServer Pages Photo Album application, or both of these applications.

2.3.4.1 Handling the Setting of Properties for Unknown Image Formats

The IMUtil class of the interMedia Java sample application called IMExample, contains utility methods for common image functions. One of these methods is the setProperties( ) method. The static method takes an OrdImage object as an input parameter and calls the setProperties( ) method on the object.

static boolean setProperties(OrdImage img)
  {
    try
    {
      img.setProperties();
      return true;
    }
    catch (SQLException e)
    {
      return false;
    }
  }

If an exception is thrown, the setProperties( ) method returns false to indicate failure; otherwise it returns true.

See Chapter 4 for a full description of the IMExample application and for more information about using the setProperties( ) method in a Java application.

2.3.4.2 Handling Image Processing for Unknown Image Formats

In the insertNewPhoto( ) method in both the PhotoAlbumServlet class of the interMedia Java Servlet Photo Album application and in the PhotoAlbumBean class of the interMedia JavaServer Pages Photo Album application, a new photograph is inserted into the photo album, creating a thumbnail image at the same time. If the application tries to process an image in cases when the image format is unknown, then when the application calls the processCopy( ) method, the application will always fail. To work around this potential problem, the application uses the following try block and catch block to catch any SQL exceptions:

try
        {
            image.processCopy( "maxScale=50,50", thumb );
        }
        catch ( SQLException e )
        {
            thumb.deleteContent();
            thumb.setContentLength( 0 );
        }

In this example, when the image format is unknown and a thumbnail image cannot be created, the application catches the SQL exception and calls the deleteContent( ) method to delete the content of the thumbnail image, and then calls the setContentLength( ) method to set its length to zero.

2.4 Developing Java-Based Web Applications

On the Java platform, a Web application is a dynamic extension of a Web server. A Java-based Web application is composed of Java servlets, JavaServer Pages (JSP), or both. Java servlets are Java classes that dynamically process HTTP requests and construct HTTP responses. JavaServer Pages are text-based documents that execute as servlets but that allow a more natural approach to creating static content.

Oracle interMedia Java Classes for Servlets and JSP is based on Oracle interMedia Java Classes. The classes in Oracle interMedia Java Classes for Servlets and JSP facilitate the retrieval and uploading of media data from and to Oracle Database in a Java-based Web application.

Like the Java classes in Oracle interMedia Java Classes, these Java classes are included in the oracle.ord.im.* package. The classes are as follows:

The OrdHttpResponseHandler class facilitates the retrieval of the media data from Oracle Database and its delivery to an HTTP client from a Java servlet. The OrdHttpJspResponseHandler class provides the same features for JSP pages. The OrdHttpUploadFormData, OrdHttpUploadFile, OrdMultipartFilter, and OrdMultipartWrapper classes facilitate the uploading of media data from a Web client to Oracle Database.

Section 2.4.1 describes how to retrieve media data from interMedia objects in a Java-based Web application. Section 2.4.2 describes how to upload media data into database interMedia objects in a Java-based Web application.

Before you can begin using interMedia Java Classes for Servlets and JSP, you must set up your environment with the appropriate Java libraries, as described in Step 1, Section 2.3.1. In addition to the items in that list, you must include the Oracle interMedia Java Web library <ORACLE_HOME>/ord/jlib/ordhttp.jar in your CLASSPATH environment variable.

See Oracle interMedia Java Classes for Servlets and JSP API Reference for details about the available methods in these classes.

2.4.1 Media Retrieval in Java-Based Web Applications

In general, displaying a Web page that contains images in a Web browser requires two HTTP round trips.

In the first trip, the Web browser makes an HTTP request to the URL of the Web page that contains the images. The Web server responds with the Web page text content and the URLs for the media content. The URL is the src attribute of the <img> tag in the Web page.

In the second trip, the Web browser makes another HTTP request to the URL in the <img> tag to get the image binary data, and then displays the image in the browser.

In a Java-based Web application, sending media data from the database to an HTTP client (Web browser) requires the proper media URL (generated in the first HTTP response); and the proper media delivery component (a servlet or JSP for the second HTTP response).

2.4.1.1 Media URL

When media data is stored as static files on the Web server, the media URL is the relative or absolute path to the media files on the file system. When media data is stored in a database, the media URL is generally composed of a media delivery component (a servlet or JSP) and the parameters for the media delivery component. The media delivery component is the target for the second HTTP request to retrieve the media data. The parameters for the media delivery component are used by the media delivery component to query and locate the media data in the database. For example:

<img src="OrdGetMedia.jsp?id=1"/>

where OrdGetMedia.jsp in the media URL "OrdGetMedia.jsp?id=1" is the media delivery component, and id=1 is the parameter to the media delivery component.

2.4.1.2 Media Delivery Component

Because media data is stored in the database as interMedia objects, the media delivery component must dynamically retrieve the media data as Java objects (see Section 2.3.2), based on certain query conditions. Then, you can use either the OrdHttpResponseHandler or the OrdHttpJspResponsehandler class in Oracle interMedia Java Classes for Servlets and JSP to deliver the data to the HTTP client (Web browser).

The following example demonstrates the use of a Java servlet as the media delivery component, and highlights in bold the SQL statements and significant areas in the code where this operation takes place.

import oracle.ord.im.OrdHttpResponseHandler;
 
protected void doGet(HttpServletRequest request,
 HttpServletResponse response)
  throws ServletException, java.io.IOException
{
// obtain oracle.ord.im.OrdImage object 
// imgProxy follows the Section "Media Retrieval in Java"
 . . . 
 
// deliver the image data to the browser
OrdHttpResponseHandler handler = 
new OrdHttpResponseHandler( request, response);
handler.sendImage(imgProxy);
 
 . . . 
 }

The following example demonstrates the use of a JSP page as the media delivery component, and highlights in bold the SQL statements and significant areas in the code where this operation takes place.

<%@ page 
import="oracle.ord.im.OrdHttpJspResponseHandler" 
%>
 
<jsp:useBean id = "handler" scope="page"
     class = "oracle.ord.im.OrdHttpJspResponseHandler" 
/>
 
<%
// obtain oracle.ord.im.OrdImage object 
// imgProxy follows the Section "Media Retrieval in Java"
. . . 
 
// deliver the image data to the browser
   handler.setPageContext( pageContext );
   handler.sendImage(imgProxy);
   return;
%>

2.4.2 Media Upload in Java-Based Web Applications

The HTML form allows you to input and upload data from a Web browser to a Web server for processing. The following HTML code segment is an example of the HTML form that uploads a file. This code example highlights in bold the SQL statements and areas in the code where this operation takes place.

<form action="uploadAction.jsp" method="post" 
enctype="multipart/form-data">
id: <input type="text" name="id"/>
description: <input type="text" name="description"/>
Photo: <input type="file" name="photo"/>
</form>

Referring to the preceding code example, setting the value of the enctype attribute in the <form> tag to "multipart/form-data" specifies multipart/form-data format encoding of the uploaded data. The value of the action attribute in the <form> tag represents the name of the JSP that will handle the uploaded data.

To handle the uploaded data in a JSP or servlet, follow these steps:

  1. Decode the uploaded file. Because this file is encoded in multipart/form-data format, the data must be decoded before further processing can proceed. You can use the OrdHttpUploadFormData class to decode the encoded HTTP request data and obtain the uploaded file as an instance of the OrdHttpUploadFile object. You can use this class explicitly or implicitly to get the decoded uploaded file.

    The following example demonstrates how to use the OrdHttpUploadFormData class explicitly to get the uploaded file, and highlights in bold the SQL statements and significant areas in the code where this operation takes place. Use this method within the servlet or JSP that handles the upload HTTP request.

    //
    // Import OrdHttpUploadFormData and OrdHttpUploadFile class:
    // In a servlet:
    // import oracle.ord.im.OrdHttpUploadFormData;
    // import oracle.ord.im.OrdHttpUploadFile;
    // In a JSP:
    // <%@ page import="oracle.ord.im.OrdHttpUploadFormData" %>
    // <%@ page import="oracle.ord.im.OrdHttpUploadFile" %>
    //
     
    //
    // Following code snippets should be within <% %> if in a JSP.
    //
     
    // Create an OrdHttpUploadFormData object and use it to parse 
    // the multipart/form-data message.
    //
    OrdHttpUploadFormData formData = new OrdHttpUploadFormData(
     request );
    formData.parseFormData();
     
    //
    // Get the description, location, and photo.
    //
    String id = formData.getParameter( "id" );
    String description = formData.getParameter( "description" );
    OrdHttpUploadFile photo = formData.getFileParameter( "photo" );
     
    //
    // Process the uploaded file
    //
     ...
     
    //
    // Release the resources
    //
    formData.release();
    
    

    To avoid instantiating and releasing the OrdHttpUploadFormData class explicitly in each JSP or servlet that handles the uploaded data, you can use the OrdHttpUploadFormData class implicitly by configuring the Web application with the OrdMultipartFilter class. Using the OrdMultipartFilter class ensures that any HTTP request that is encoded in multipart/form-data format will be decoded and passed along to the JSP or servlet that further processes the request.

    The following substeps and accompanying examples describe how to use the OrdHttpUploadFormData class implicitly to get the uploaded file. These code examples highlight in bold the SQL statements and significant areas in the code where this operation takes place.

    1. Configure the filter by adding the following code to the web.xml file in your Web application:

      <filter>
          <filter-name>OrdMultipartFilter</filter-name>
          <filter-class>
      oracle.ord.im.OrdMultipartFilter
          </filter-class>
      </filter>
      <filter-mapping>
          <filter-name>OrdMultipartFilter</filter-name>
          <servlet-name>*.jsp</servlet-name>
      </filter-mapping>
      
      
    2. Obtain the form data and the uploaded file in the JSP or servlet after the filter is configured:

      //
      // Get the id, description, and photo.
      //
      String id = request.getParameter( "id" );
      String description = request.getParameter( "description" );   oracle.ord.im.OrdHttpUploadFile photoFile = 
       request.getFileParameter("photo");
      
      

      where request is the HttpServletRequest object passed to the JSP or servlet.

  2. Save the uploaded file to the database. After the OrdHttpUploadFile object is obtained by explicitly or implicitly using the OrdHttpUploadFormData class, the uploaded file is ready to be loaded into an interMedia object in the database, using the following statement:

    photoFile.loadImage(imgProxy);
    
    

    where photoFile is the OrdHttpUploadFile object andimgProxy is an OrdImage object obtained in Step 1 in Section 2.3.3.

    The loadImage method implicitly calls the setProperties method to populate the object fields.

    After the data is loaded into the interMedia Java object, you can update the corresponding interMedia object in the database table by following Steps 4 and 5 in Section 2.3.3.