Skip Headers

Oracle® interMedia Annotator User's Guide
Release 9.2
Part No. A96120-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

3
Annotator Engine API Example

This chapter provides a description of a sample program that parses a media source file, creates an annotation, and uploads the annotation to an Oracle database. This program, SimpleAnnotator.java, is an example of a user-developed application that was written using the Oracle interMedia Annotator engine API.

You can find the source code at the following location:

In addition, an asynchronous version of the sample program, named SimpleAnnotatorAsynch.java, is available in the same directory.

The code that appears in this chapter will not necessarily match the code shipped as SimpleAnnotator.java. If you want to run this sample program on your system, use the file provided with the installation; do not attempt to compile and run the code presented in this chapter.


Note:

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

The sample program contains user-defined methods that use Java and Oracle interMedia Annotator APIs to perform the following operations:


Note:

Oracle interMedia Annotator cannot change the attribute values in the media itself; it can change only the attribute values in the extracted annotation. If you parse the media file again, your annotation will be overwritten and any attributes that you have edited will revert to their original values.

3.1 Import Statements

Example 3-1 shows the import statements that must be included in the application to properly run an Annotator client.

Example 3-1 Import Statements

import java.net.*;

import java.io.*;

import java.util.*;

import java.text.*;

import java.sql.*;


import oracle.ord.media.annotator.handlers.annotation.*;

import oracle.ord.media.annotator.annotations.Attribute;

import oracle.ord.media.annotator.annotations.Annotation;

import oracle.ord.media.annotator.listeners.*;

import oracle.ord.media.annotator.handlers.*;

import oracle.ord.media.annotator.handlers.db.*;

import oracle.ord.media.annotator.utils.*;

import oracle.ord.media.annotator.AnnotatorException;

3.2 Class Definition and Instance Variables

Example 3-2 shows the class definition and instance variables for the sample Annotator client.

Example 3-2 Class Definition and Instance Variables

public class SimpleAnnotator implements AnnListener, OutputListener{

     private Status m_st;

     private AnnotationHandler m_ah;

     static String m_output_file;

     static boolean m_output_file_defined;

An Annotator client must implement the AnnListener interface to have access to the callback methods used for Annotator engine operations. See "Class oracle.ord.media.annotator.listener.AnnListener" for more information.

An Annotator client must implement OutputListener to get access to trace information from the engine. See "Class oracle.ord.media.annotator.listener.OutputListener" for more information.

The class contains two instance variables:

Two additional variables are declared. The variable m_output_file will hold the name of the output file. The variable m_output_file_defined is a Boolean that will indicate if an output file has been passed as an argument.

3.3 main( ) Method

The main( ) method in the sample program tests the URL passed to the application, creates an empty instance of SimpleAnnotator, and calls the init( ) method. After the instance is initialized, it invokes a method that parses the media. Example 3-3 shows the contents of the main( ) method.

Example 3-3 main( ) Method (SimpleAnnotator)

 [1] public static void main(String[] argv){

 [2] if(argv.length == 0 )

       {

         System.err.println("Usage: java SimpleAnnotator mediaURL [-w xmlfile] [-e enc]");

         System.err.println("mediaURL: URL of the media you want to parse");

         System.err.println("          (for example. file:/myjpeg.jpg");

         System.err.println("xmlfile: The output file for XML annotations");

         System.err.println("encoding: an optional argument of the character");

         System.err.println("            encoding of the media");

        return;

       }


 [3] String szURL = argv[0];

     String szEncoding=null;

     boolean encoding_define=false;

     m_output_file_defined=false;


 [4] for(int i=1; i<argv.length; i++) {

       if (argv[i].charAT(0) == '-') {


         if (argv[i].charAT(1) == 'w') {

           if (i == argv.length - 1) break;

           int j = i+1;

           if (argv[j].charAT(0) != '-') {

              m_output_file_defined=true;

              m_output_file = argv[j];

              i++

           }

         }

         if (argv[i].charAT(1) == 'e') {

           if (i == argv.length - 1) break;

           int j = i+1;

           if (argv[j].charAT(0) != '-') {

              encoding_defined=true;

              szEncoding =argv[j];

              i++;

           }

         }

       }

     }


 [5] SimpleAnnotator sa = new SimpleAnnotator();

 [6] sa.init();


 [7]   if (encoding_defined) 

       {

           sa.parse(szURL, szEncoding]);

       }

         else

         {

         sa.parse(szURL);

         }

}

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

  1. Accepts the URL of the media source file to be operated upon as the first argument. Optional arguments are:

    • A String representing the output file for the XML annotations.

    • A String representing the character encoding of the media.

  2. Tests to make sure the URL of the media source file to be parsed was passed as an argument. If there are no arguments, an error message is printed.

  3. Defines the following variables:

    • A String named szURL. Its value is set to the value of the first parameter, the URL of the media source file.

    • A String named szEncoding, representing the character encoding of the media. Its value is set to null.

    • A Boolean named encoding_defined that defines whether or not an argument for the character encoding is passed to the method.

    In addition, sets the value of the m_output_file_defined variable to false.

  4. Tests to see how many arguments were passed to the method and assigns values to variables.

  5. Creates an empty instance of SimpleAnnotator.

  6. Calls the init( ) method to initialize the newly created SimpleAnnotator instance. Section 3.4 describes the init( ) method and lists its code.

    After the SimpleAnnotator instance is initialized, the client can invoke the Annotator engine operations, such as parsing, extraction, and insertion.

  7. Calls the parse( ) method to parse the media source file. It passes the string containing the URL and, if supplied, the encoding method.

    Section 3.5 describes the parse( ) method and lists its code.

3.4 init( ) Method

The init( ) method in the sample program initializes the Annotator client and sets preferences. Example 3-4 shows the contents of this method.

Example 3-4 init( ) Method

public void init(){

     [1] report("Initializing Annotator Engine..."); 


     [2] Status.initStatus(this);

     [3] m_st = Status.getStatus();

     [4] m_st.SetOutputMode(Status.OUTPUT_MODE_VERBOSE);


     [5] try { 

          m_ah = new AnnotationHandler(AnnotationHandler.OP_MODE_SYNCH);

     } 

     [6] catch(Exception e) { 

          report("Initializing... Failed."); 

          reportError(e); 

     }


     [7] Preferences prefs = Preferences.getPrefs();

     [8] prefs.setProperty(SZ_CONN_PASSWORD, "mypassword");


     [9] report("Initializing Annotator Engine... Done");

}

The code in the init( ) method performs the following actions:

  1. Prints a message that the initialization is beginning. See Section 3.12 for more information on the report(String) method.

  2. Initializes the Status object and implements the OutputListener interface so that the current instance of SimpleAnnotator can receive the status messages. See "initStatus( )" for more information.

  3. Sets the initialized Status object to the m_st instance variable.

  4. Uses the Status.SetOutputMode( ) method to set the status output mode to VERBOSE. See "SetOutputMode( )" for more information.

  5. Creates a new AnnotationHandler instance in synchronous mode and sets it to the m_ah instance variable.

  6. Catches any exceptions that were raised in the previous step and prints the error to the screen with the report( ) and reportError( ) methods. See Section 3.15 for more information on the reportError( ) method.

    If the Status and AnnotationHandler objects were both created with no errors, you can set any necessary preferences.

  7. Creates a Preferences object and initializes it.

  8. Uses the Preferences.setProperty( ) method to set a new preference named SZ_CONN_PASSWORD. See "setProperty( )" for more information.

  9. Prints a message that initialization was successful.

3.5 parse( ) Method

The parse(String) method in the sample program calls the method AnnotationHandler.parseMedia( ), passing the URL, to parse the source file and create the annotation. Example 3-5 shows the contents of the parse(String) method.

Example 3-5 parse(String ) Method

public void parse(String szURL){

     if(m_ah != null){

          AnnTaskMonitor atm = m_ah.parseMedia(szURL, this); 

     }

}

The code in the parse(String) method calls the AnnotationHandler.parseMedia( ) method and passes the URL to it. The client (this) implements the AnnListener interface.

The parse(String, String) method in the sample program calls the AnnotationHandler.parseMedia( ) method, passing the URL and character encoding, to parse the source file and create the annotation. Example 3-6 shows the contents of the parse(String, String) method.

Example 3-6 Parse(String, String) Method

public void parse(String szURL, String enc){

     if(m_ah != null){

          AnnTaskMonitor atm = m_ah.parseMedia(szURL, this, enc); 

     }

}

The code in the parse(String, String) method calls the AnnotationHandler.parseMedia( ) method and passes the URL and the character encoding to it. The client (this) implements the AnnListener interface.

See "parseMedia(String, AnnListener)" and "parseMedia(String, AnnListener, String)" for more information about the AnnotationHandler.parseMedia( ) method.

If the annotation handler has been initialized properly in the init( ) method, the AnnotationHandler.parseMedia( ) method is called.

The AnnotationHandler.parseMedia( ) method parses the source file and builds the annotation. Then, it calls the AnnListener.parsePerformed( ) call-back function. This method is overridden in the SimpleAnnotator class, so the actual method called is SimpleAnnotator.parsePerformed( ). See Section 3.6 for more information.

3.6 parsePerformed( ) Method

The parsePerformed( ) method in the sample program manipulates the annotation before it is uploaded to the database. Because your application must implement AnnListener, this method is required. Example 3-7 shows the contents of the parsePerformed( ) method.

Example 3-7 parsePerformed( ) Method

public void parsePerformed(Annotation ann){

 [1] if(ann != null) {

 [2]  String szMimeType = (String) ann.getAttribute("MEDIA_SOURCE_MIME_TYPE");

               

 [3]  Enumeration eAttrs = ann.getAttributes();

      while(eAttrs.hasMoreElements()){

        try {

 [4]      Object att_val = eAttrs.nextElement();

        }

        Catch (Exeption e) {

          System.err.println ("exception caught " + e.getMessage());

        }

 [5] Enumeration eSubAnns = ann.getSubAnnotations();

     while (eSubAnns.hasMoreElements()){

 [6] Annotation subAnn = (Annotation)eSubAnns.nextElement();

     }

     // Advanced Example

     try {

 [7] Annotation inventoryAnn = m_ah.createAnnotationByName("InventoryAnn");

 [8] ann.addSubAnnotation(inventoryAnn);

 [9] inventoryAnn.setAttribute("SALES_PRICE", new Float(19.99));

     }

 [10] catch (AnnotatorException ae){

            errorOccured(ann, ae);

            return;

       }

 [11] report(ann);

     }

 [12] if(m_ah.isExtractable(ann)){

 [13] m_ah.extractMedia(ann, this);

     }

}

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

  1. Executes the code in the next block only if a valid annotation was passed by the caller.

    If the caller did pass a valid annotation, you would typically manipulate the annotation before it is uploaded to the database. Steps 2 through 11 show examples of the kinds of operations you may perform. The tasks in steps 7 through 10 should be used only by advanced programmers.

  2. Uses the Annotation.getAttribute( ) method to retrieve the value of the MEDIA_SOURCE_MIME_TYPE attribute of the annotation and casts it into a String object. See "getAttribute( )" for more information.

  3. Uses the Annotation.getAttributes( ) method to get a list of all attributes that have a valid value and stores their names in an Enumeration object. See "getAttributes( )" for more information.

  4. Accesses the values stored in the Enumeration object.

  5. Uses the Annotation.getSubAnnotations( ) method to get all subannotations of the annotation and stores them in an Enumeration object. See "getSubAnnotations( )" for more information.

  6. Accesses the values stored in the Enumeration object.

  7. Creates an empty annotation named inventoryAnn.

  8. Uses the Annotation.addSubAnnotation( ) method to add inventoryAnn to ann as a subannotation. See "addSubAnnotation( )" for more information.

  9. Uses the Annotation.setAttribute( ) method to set the SALES_PRICE attribute in inventoryAnn to 19.99. See "setAttribute( )" for more information.

  10. Catches any errors raised in steps 7 through 9 and reports them with the errorOccured( ) method, which is discussed in Section 3.10.

  11. Uses the report(Annotation) method, which is discussed in Section 3.13, to print the annotation as an XML file.

  12. Checks to see if it is possible to extract samples from the annotation or any of its subannotations. If it is possible, the code in step 13 is executed. If not, that step is omitted.

  13. Uses the AnnotationHandler.extractMedia( ) method to extract the media samples from the annotation. See "extractMedia( )" for more information.

    When AnnotationHandler.extractMedia( ) has finished, it calls the call-back function AnnListener.extractionPerformed( ). This method is overridden in the SimpleAnnotator class, so the actual method called is SimpleAnnotator.extractionPerformed( ). This method is discussed in Section 3.7.

3.7 extractionPerformed( ) Method

The extractionPerformed( ) method in the sample program maps an annotation to a file and uploads the annotation to the database. Because your application must implement AnnListener, this method is required. Example 3-8 shows the contents of the extractionPerformed( ) method.

Example 3-8 extractionPerformed( ) Method

public void extractionPerformed(Annotation ann){

     [1] report(ann);

     [2] OrdFileMapping ofm = new OrdFileMapping("e:\\mylogic.ofm");

     [3] m_ah.insertMedia(ann, ofm, this);

}

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

  1. Uses the report(Annotation) method, which is discussed in Section 3.13, to print the annotation as an XML file.

  2. Creates a new OrdFileMapping object based on the mapping file. For this example, the mapping file is located at e:\\mylogic.ofm. See "OrdFileMapping Constructor" for more information.

  3. Uploads the annotation to the database, using the OrdFileMapping object to map the contents of the annotation to the proper locations on the database and the AnnotationHandler.insertMedia( ) method to insert the media. See "insertMedia(Annotation, OrdMapping, AnnListener)" for more information on this method.

    Alternatively, you could specify a Connection object that represents the JDBC connection to be used in the upload process. The same JDBC connection can be used for multiple upload operations. See "insertMedia(Annotation, OrdMapping, AnnListener, Connection)" for more information.

    When AnnotationHandler.insertMedia( ) has finished, it calls the call-back function AnnListener.insertionPerformed( ). This method is overridden in the SimpleAnnotator class, so the actual method called is SimpleAnnotator.insertionPerformed( ), which is discussed in Section 3.8.

3.8 insertionPerformed( ) Method

The insertionPerformed( ) method in the sample program closes the connection to the database and catches any exceptions. Because your application must implement AnnListener, this method is required. Example 3-9 shows the contents of the insertionPerformed( ) method.

Example 3-9 insertionPerformed( ) Method

public void insertionPerformed(Annotation ann, Connection conn){ 

        try {

  [1]   conn.commit();

  [2]   conn.close();

        }

  [3]   catch (SQLException sqle){ errorOccured(ann, sqle); }

}

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

  1. Commits all changes made to the database.

  2. Closes the connection to the database.

    Instead of closing the connection, the client could reuse the connection by passing it to another AnnotationHandler call.

  3. Catches any errors raised in steps 1 and 2 and reports them with the errorOccured( ) method. See Section 3.10 for more information on the errorOccured( ) method.

3.9 warningOccured( ) Method

The warningOccured( ) method in the sample program captures any warnings. Because your application must implement AnnListener, this method is required. Example 3-10 shows the contents of the warningOccured( ) method.

Example 3-10 warningOccured( ) Method

public void warningOccured(Annotation ann, Exception e){ 

     reportError(e); 

}

The code in the warningOccured( ) method implements the AnnListener.warningOccured( ) method. This method uses the reportError( ) method, discussed in Section 3.15, to capture the warning and report it. If a warning occurs and this method is called, the Annotator engine continues to operate. See warningOccured( ) for more information.

3.10 errorOccured( ) Method

The errorOccured( ) method in the sample program captures any errors. Because your application must implement AnnListener, this method is required. Example 3-11 shows the contents of the errorOccured( ) method.

Example 3-11 errorOccured( ) Method

public void errorOccured(Annotation ann, Exception e){

     reportError(e);

}

The code in the errorOccured( ) method implements the AnnListener.errorOccured( ) method. This method uses the reportError( ) method, discussed in Section 3.15, to capture the error and report it. If an error occurs and this method is called, the Annotator engine will not continue to operate. See "errorOccured( )" for more information.

3.11 ConsoleOutput( ) Method

The ConsoleOutput( ) method in the sample program prints messages during execution. Because your application must implement OutputListener, this method is required. Example 3-12 shows contents of the ConsoleOutput( ) method.

Example 3-12 ConsoleOutput( ) Method

public void ConsoleOutput(String sz){

     report(sz);

}

The code in this example implements the OutputListener.ConsoleOutput( ) method. This method uses the report(String) method, discussed in Section 3.12, to print messages during execution. See "ConsoleOutput( )" for more information.

3.12 report(String) Method

The report(String) method in the sample program prints strings to the error stream. Example 3-13 shows contents of the method.

Example 3-13 report(String) Method

public void report(String szValue){

     System.err.println(szValue);

}

The code in the report(String) method prints the given stream to the error stream.

3.13 report(Annotation) Method

The report(Annotation) method in the sample program prints the annotation to an XML file. Example 3-14 shows the contents of the method.

Example 3-14 report(Annotation) Method

public void report(Annotation ann){

 [1]  try

      {

        File tmp_file;

        if (m_output_file_defined)

        {

           tmp_file = new File(m_output_file);

        }

        else

        {  tmp_file = File.createTempFile("xml", ".dat");

        }

        System.out.println ("created file to save annotation:"

                             + tmp_file.getPath());

 [2]    FileOutputStream fo = new FileOutputStream (tmp_file);

        OutputStreamWriter w = new OutputStreamWriter(fo, "UTF-8");

 [3]    m_ah.exportToXML(w, ann);

        w.flush();

        w.close();

        fo.close();

}

 catch (Exception e) { reportError(e);   }

{

The code in the report(Annotation) method performs the following operations:

  1. Tests to see if a temporary output file exists and creates one if it does not.

  2. Writes the output stream to a temporary file.

  3. Uses the AnnotationHandler.exportToXML( ) method to create an XML representation of the given annotation. See "exportToXML( )" for more information.

3.14 reportWarning( ) Method

The reportWarning( ) method in the sample program prints warnings to the error stream. Example 3-15 shows the contents of the method.

Example 3-15 reportWarning( ) Method

public void reportWarning(Exception e){

     report("WARNING:");

     reportError(e);

}

This method uses the reportError( ) method to report the given error.

3.15 reportError( ) Method

The reportError( ) method in the sample program prints exceptions to the error stream. Example 3-16 shows the contents of the method.

Example 3-16 reportError( ) Method

public void reportError(Exception e){

     StringWriter sw = new StringWriter();

     PrintWriter  pw = new PrintWriter(sw);

     e.printStackTrace(pw);

     report(sw.toString());

}

The code in the reportError( ) method captures the contents of the exception, casts them into a String object, and uses the report(String) method to print the exception to the error stream.




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