Sedna LogoBackground Top
 
Home  |  Getting Started  |  Documentation  |  Demo  |  Download  |  Support 

1.1 Java API

The Java API provides programmatic access to XML data from the Java programming language. Using the Java API, applications written in the Java can access one or more databases of the Sedna DBMS and manipulate database data using the database language described in Section 2.

Application working with the Sedna DBMS through the Java API operates with the following notions of the Java API: session, transaction, statement, result.

  1.1.1 Sessions
  1.1.2 Transactions Management
  1.1.3 Statements
  1.1.4 Results
  1.1.5 Exceptions
  1.1.6 Code Example
1.1.1 Sessions

To start working with Sedna application has to open a session via establishing an authenticated connection with the server. The Java API defines the SednaConnection interface to represent a session.

To open a session application uses static method getConnection of the DatabaseManager class.

 SednaConnection getConnection(String url,  
                               String DBName,  
                               String user,  
                               String password)  
     throws DriverException

Parameters:

url - the name of the computer where the Sedna DBMS is running. This parameter may contain a port number. If the port number is not specified, the default port number (5050) is used.

DBName - the name of the database to connect.

user - user name.

password - user password.

If the connection is established and authentication succeeds the method returns an object that implements the SednaConnection interface. Otherwise, DriverException is thrown.

Application can close session using the close method of the SednaConnection interface.

 public void close() throws DriverException

If the server does not manage to close connection properly the close method throws DriverException.

The isClosed method retrieves whether this connection has been closed or not. A connection is closed if the method close has been called on it or if certain fatal errors have occurred.

 public boolean isClosed()

Setting connection into debug mode allows getting debug information when XQuery query fails due to some reason (see 2.7.2 for details). To set the connection into debug mode use setDebugMode method of SednaConnection interface:

 public void setDebugMode(boolean debug)

Parameters:

debug - set to true to turn debug mode on; set to false to turn debug mode off. Debug mode is off by default.

Sedna supports fn:trace function for debugging purpose also (see 2.7.1 for details). By default trace output is included into XQuery query result. You can turn trace output on/off using setTraceOutput method of the SednaConnection interface:

 public void setTraceOutput(boolean doTrace)

Parameters:

doTrace - set to true to turn trace output on; set to false to turn trace output off. Trace output is on by default.

1.1.2 Transactions Management

Application can execute queries and updates against specified database only in the scope of a transaction. That is, once a session has been opened, application can begin a transaction, execute statements and commit (or rollback) this transaction.

In the session transactions are processed sequentially. That is, application must commit a begun transaction before beginning a new one.

To specify transaction boundaries application uses methods of the SednaConnection interface: begin, commit.

The begin method begins a new transaction.

 public void begin() throws DriverException

If the transaction has not begun successfully the begin method throws DriverException.

The commit method commits a transaction.

 public void commit() throws DriverException

If the transaction has not been committed successfully the commit method throws DriverException.

To rollback transaction the rollback method is used.

 public void rollback() throws DriverException

If the transaction has not been rollback successfully the rollback method throws DriverException.

The Java API does not provide auto-commit mode for transactions. That is, every transaction must be explicitly started (by means of begin) and committed (by means of commit). If session is closed (by means of close) before a transaction committed, server does rollback for that transaction, and close throws DriverException.

1.1.3 Statements

The SednaStatement interface provides methods for loading documents into the database, executing statements of the database language defined in Section 2 and retrieving results that statements produce. SednaStatement object is created using the createStatement method of the SednaConnection interface:

 public SednaStatement createStatement()  
     throws DriverException

SednaStatement object may only be created on an open connection. Otherwise, the createStatement method throws DriverException.

To load the document into the database use:

 public void loadDocument(InputStream in,  
                          String doc_name)  
     throws DriverException, IOException

The in parameter is an input stream to get the document from. The doc_name parameter is the name for this document in the database.

To load the document into the specified collection of the database use:

 public void loadDocument(InputStream in,  
                          String doc_name,  
                          String col_name)  
     throws DriverException, IOException

The in parameter is an input stream to get the document from. The doc_name parameter is the name for this document in the database. The col_name parameter is the name of the collection to load the document into.

To execute a statement the execute methods of the SednaStatement are used.

 public boolean execute(String queryText)  
     throws DriverException

The queryText parameter contains the text of the statement.

 public boolean execute(InputSteram in)  
     throws DriverException

The in parameter is some input stream to read an XQuery statement from.

Some statements (such as XQuery statements or the retrieve metadata command) produce the result. In case of such statements, the execute methods return true and the result can be obtained as described in Section 1.1.4. In case of statements that do not produce the result (such as updates or bulk load), the execute methods return false.

The results of XQuery queries to the Sedna DBMS can be represented either in XML or SXML [11]. To specify the type of the result use the following extended versions of the execute method:

 boolean execute(InputStream in,  
                 ResultType resultType)  
     throws DriverException, IOException;

 boolean execute(String queryText,  
                 ResultType resultType)  
     throws DriverException, IOException;

The resultType parameter is either ResultType.XML or ResultType.SXML.

1.1.4 Results

The SednaSerializedResult interface represents the result of the statement evaluation. Application can obtain the result using the getSerializedResult method of the SednaStatement interface.

 public SednaSerializedResult getSerializedResult()

The result of the non-XQuery statement evaluation is retrieved as a sequence with only one item, where the item is a string. For example, in case of the retrieve descriptive schema command the result is a sequence with an item that is a descriptive schema represented as a string. The result of the XQuery statement evaluation is retrieved as a sequence of items, where every item is represented as a string.

Application can use the next methods of the SednaSerializedResult interface to iterate over the result sequence:

 public String next() throws DriverException

The method returns an item of the result sequence as a string. If the sequence has ended it returns null. It throws DriverException in the case of error.

 public int next(Writer writer) throws DriverException

The method writes an item of the result sequence to some output stream using writer. It returns 0 if an item was retrieved and written successful, and 1 if the result sequence has ended. It throws DriverException in the case of error.

Please, notice, that in the current version of the Sedna DBMS application has to execute statements and use the results of their execution sequentially. To explain this note, suppose application execute a statement, obtains a result of that statement execution and iterates over this result. If, after that, application executes next statement, it cannot iterate over the result of the previous statement any more.

1.1.5 Exceptions

The DriverException class provides information about errors that occur while application works with the Sedna DBMS through the Java API. DriverException is also thrown when application loses its connection with the server.

1.1.6 Code Example

In this section we provide an example program that uses the Java API to work with Sedna DBMS. This application connects to the Sedna DBMS, opens a session. The session consists of one transaction. Application loads data from the file region.xml and executes the XQuery statement. When statement is executed, application drop the document, commits the transaction and closes the session.

import ru.ispras.sedna.driver.*;  
class Client {  
  public static void main(String args[]) {  
 
    SednaConnection con = null;  
    try {  
      /* Get a connection */  
      con = DatabaseManager.getConnection("localhost",  
                                          "testdb",  
                                          "SYSTEM",  
                                          "MANAGER");  
 
      /* Begin a new transaction */  
      con.begin();  
 
      /* Create statement */  
      SednaStatement st = con.createStatement();  
 
      /* Load XML into the database */  
      System.out.println("Loading data ...");  
      boolean res;  
      res = st.execute("LOAD ’C:/region.xml’ ’region’");  
 
      System.out.println("Document ’region.xml’ "+  
          "has been loaded successfully");  
      /* Execute query */  
      System.out.println("Executing query");  
      res = st.execute("doc(’region’)/*/*");  
 
      /* Print query results */  
      printQueryResults(st);  
 
      /* Remove document */  
      System.out.println("Removing document ...");  
      res = st.execute("DROP DOCUMENT ’region’");  
 
      System.out.println("Document ’region’ " +  
                 "has been dropped successfully");  
      /* Commit current transaction */  
      con.commit();  
    }  
    catch(DriverException e) {  
        e.printStackTrace();  
    }  
    finally {  
      /* Properly close connection */  
      try { if(con != null) con.close(); }  
      catch(DriverException e) {  
        e.printStackTrace();  
      }  
    }  
  }  
 
  /* Pretty printing for query results */  
  private static void printQueryResults(SednaStatement st)  
    throws DriverException {  
    int count = 1;  
    String item;  
    SednaSerializedResult pr = st.getSerializedResult();  
    while ((item = pr.next()) != null) {  
      System.out.println(count + " item: " + item);  
      count++;  
    }  
  }  
}

The full-version source code of this example program can be found at:

[win:] INSTALL_DIR\examples\api\java\Client.java  
[nix:] INSTALL_DIR/examples/api/java/Client.java

where INSTALL_DIR refers to the directory where Sedna is installed.

Before running the example make sure that the Sedna DBMS is installed and do the following steps:

  1. Start Sedna by running the following command:
    se_gov

    If Sedna is started successfully it prints ”GOVERNOR has been started in the background mode”.

  2. Create a new database testdb by running the following command:
    se_cdb testdb

    If the database is created successfully it prints ”The database ’testdb’ has been created successfully”.

  3. Start the testdb database by running the following command:
    se_sm testdb

    If the database is started successfully it prints ”SM has been started in the background mode”.

You can compile and run the example following the steps listed below:

  1. To compile the example, run the script:
        [win:] Clientbuild.bat  
        [nix:] ./Clientbuild.sh

    located in the same folder as Client.java.

  2. To run the compiled example, use the script:
        [win:] Client.bat  
        [nix:] ./Client.sh

    located in the same folder as Client.java.