To manage manual and automatic synchronization, Native (C) APIs and Java APIs are available for Win32, Windows Mobile and Linux clients. In addition, .NET APIs are also available for manual and automatic synchronization on Win32 and Windows Mobile clients. Native APIs are implemented in the following:
The ose.dll(libose.so on linux) implements manual synchronization APIs - both OSE (11g or later API) and OCAPI (10. 3 and earlier API for manual synchronization for backward compatibility, implemented as a wrapper around the new API). In MDK, OSE APIs are declared in ose.h and OCAPI APIs are declared in ocapi.h (see Section 3.1.1.2, "OSE Synchronization APIs For Native Applications").
The bgsync.dll(libbgsync.so on linux) implements automatic synchronization control APIs (new 11g APIs). In MDK, these APIs are declared in bgsync.h (see Section 3.2.1.2.1, "Overview") .
The olSyncAgent.dll (libautosync.so on linux) implements older 10.3 automatic synchronization control APIs for backward compatibility (see Section 3.2.1.4, "OCAPI Sync Control APIs"). In MDK, these APIs are declared in olite_bgsync.h. Java APIs for these platforms are implemented in jsync.jar. In addition, jsync.jar uses JNI code implemented in msync_java.dll (libmsync_java.so on linux).
To call native APIs on Win32, Linux and Windows Mobile do the following:
For Win32, ensure that all client dlls (both specified above and their dependencies) are in the PATH.
For Linux, ensure all the shared libraries are found in LD_LIBRARY_PATH.
For Windows Mobile, the client setup will put these dlls into \Windows directory on the device.
.NET APIs are implemented in Oracle.OpenSync.dll (see Section 3.2.1.3.1, "Overview"), which depends on all other client binaries, so the requirement above also applies.
Note:
To call Java APIs on Win32, Windows Mobile and Linux, in addition to above requirements, make sure that msync_java.dll(libmsync_java.so on linux) is also found in PATH (LD_LIBRARY_PATH on linux).Ensure that jsync.jar is in the CLASSPATH.
Note:
The dlls/shared libraries in MDK are located in <MOBILE_HOME>\Mobile\Sdk\bin and the header files are located at <MOBILE_HOME>\Mobile\Sdk\include.Note:
For iOS clients:Both SQLite and Berkeley DB clients are supported. The iOS sync APIs for SQLite client are implemented in libosync.a static library which you link with the application.
For Berkeley DB client, the static library name is libosync_bdb.a.
The iOS clients support native manual synchronization APIs (See Section 3.1.1.2, "OSE Synchronization APIs For Native Applications") as well as automatic synchronization APIs (See Section 3.2.1.2, "Native APIs for the Sync Agent and Automatic Synchronization").
Older 10.3 APIs (OCAPI) and Java APIs are not supported.
Note:
Limitations of iOS client:The iOS client runs within the user's application and can only access database files stored within the application sandbox. Also, like Android and Java SE clients (as mentioned below), syncagent only runs within the application process.
For Android and Blackberry platforms, all synchronization functionality is implemented in pure java. For Android, SQLite client library is osync_android.jar and Berkeley DB client is osync_bdb_android.jar, located in MDK under the following:
<MOBILE_HOME>\Mobile\Sdk\android\lib
<MOBILE_HOME>\Mobile\Sdk\android\lib\bdb.
Note:
The Android Berkeley DB client also requires Berkeley DB jdbc driver (sqlite.jar) and Berkeley DB native library (liboracle-jdbc.so, located in MDK under <MOBILE_HOME>\Mobile\Sdk\android\lib\bdb\armeabi) and the Blackberry client library is in osync_rim.jar (in MDK under <MOBILE_HOME>\Mobile\Sdk\blackberry\lib.The actual binaries installed on the device are osync_rim*.cod files under <MOBILE_HOME>\Mobile\Sdk\blackberry, but osync_rim.jar will be used for building mobile application).
Note:
Automatic synchronization is not currently supported for Blackberry client.The pure java client referred as Pure Java SE (PJ SE) runs on Win32 and Linux (and even Windows Mobile). The client libraries used for Berkeley DB, SQLite and Java DB PJ SE are osync_se_bdb.jar, osync_se_sqlite.jar and osync_se_javadb.jar respectively, we call it PJ SE client library file in this document (in MDK located in <ORACLE_HOME>\Mobile\Sdk\bin . Note the following:
There are both Berkeley DB, SQLite and Java DB PJ SE clients.
The settings in ose.ini are used to configure whether Berkeley DB, SQLite or Java DB client is used. See Section A 1.1 "OSE Parameter - OSE" of the Mobile Client Guide for more details on the parameters.
Once these settings are set, they should not be changed.
PJ SE client uses Berkeley DB, SQLite or Java DB JDBC driver so there is a dependency on the JDBC driver jar file, JNI and other native libraries used to implement the JDBC driver.
Ensure that both PJ SE client library file (osync_se_bdb.jar, osync_se_sqlite.jar or osync_se_javadb.jar) and the jdbc driver are in CLASSPATH and dependent native libraries are in the PATH (LD_LIBRARY_PATH on linux).
Note:
PJ SE client has the same design and limitations for automatic synchronization as PJ Android client, that is, the syncagent only runs within application process and not outside of it.Versions of compilers and run time libraries are listed in the following table:
Table 3-1 Compiler and Run Time Library Versions
APIs Language | Compiler Version | Run Time Library Version |
---|---|---|
Java |
Oracle JDK 1.6/1.7 |
Oracle JDK 1.7/1.8 |
.net |
vs 2008 |
|
vs 2008 /gcc 3.4.6 |
vs 2008 |
The following sections describe the mobile client synchronization APIs available to manage both manual and automatic synchronization programmatically within your application on the mobile client:
Besides using a tool like msync, your client side application can do synchronzation programmatically. As described above, different sets of APIs are available for different platforms, but they do represent the same functionality. Manual synchronization APIs have a concept of sync session. Using the session you can provide necessary parameters, customize synchronization options, invoke synchronization and track its progress. Use the following APIs for invoking manual synchronization on your mobile clients:
Section 3.1.1, "OSE Synchronization API for Applications on Mobile Clients"
Section 3.1.2, "SQLite Synchronization API for .Net Clients"
Section 3.1.3, "OCAPI Synchronization API for the Mobile Client"
OSE synchronization interfaces are available for pure Java clients, native clients and .Net clients. The following sections provide more details:
Note:
Use the OSE classes for all new application development for your mobile clients. These are the classes that are supported for the future.Section 3.1.1.2, "OSE Synchronization APIs For Native Applications"
Section 3.1.1.4, "OSE Synchronization JavaScript API for PhoneGap"
The following sections describe how you can use the OSE Java APIs to invoke synchronization:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.Section 3.1.1.1.5, "Custom Transport with the OSETransport Class"
Section 3.1.1.1.6, "Sequences Emulated for SQLite Mobile Clients in Replicated Environment"
The Java interface for mobile client synchronization resides in the oracle.opensync.ose
package.
The Java interface provides for the following functions:
Setting (and optionally retrieving) client-side parameters such as user name, password and server URL
Customizing syncronization with various runtime options
Invoking sync
Tracking sync progress
The following are the classes and interface for the Java API for mobile clients:
OSESession
Class
OSEProgressListener
Interface
OSETransport
Interface
OSEException
Class
OSESession
enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.
In a multi-threaded environment, you cannot execute OSESession
methods from multiple threads. Each thread should open its own session. The only exception is cancelSync
, which can be executed by another thread.
Note:
Synchronization progress is reported through theOSEProgressListener
interface, which is set by the OSESession setProgress(OSEProgressListener)
method.The parameters for the constructor are listed in Table 3-2.
OSESession( ) OSESession( String user ) OSESession( String user, char[] pwd)
Table 3-2 OSESession Class Constructor
Parameter | Description |
---|---|
|
A string containing the name used for authentication by the mobile server. |
|
A character array containing the user password. |
The public methods and their parameters for the OSESession
class are listed in Table 3-3:
Table 3-3 OSESession Class Public Method Parameters
Method | Description |
---|---|
|
Attempts to cancel the synchronization process with a non-blocking call. If successful, throws |
|
Closes any active database connections that the session maintains. This method is called before application exits. |
|
The The |
|
Provided the publication name, adds the publication to the list of publications to be synchronized selectively. See Section 3.1.1.1.4, "Selective Synchronization" for more information. |
|
Sets or retrieves the current root directory, as set in the |
|
Sets or returns |
|
Sets or retrieves the current encryption type. Possible types can are as follows:
|
|
Set to wipe out all of the client data and replace it with server data, if true. Retrieves value of force refresh. |
|
This is used to set and get the flag for persistently saving the user password. If true, the password is saved. |
|
Allows clients to modify their password on the server. After a successful synchronization, the client's password on the server is changed to the new password. |
|
Provide or modify the mobile client password. |
|
Set synchronization progress listener. For more details, see Section 3.1.1.1.3, "OSEProgressListener Interface". |
|
Sets or returns the current HTTP proxy, which can be the hostname or IP address of the proxy server. NULL is returned if proxy is not used. |
|
Sets or retrieves a flag that indicates whether the application client updates should be downloaded during the next synchronization. If set to |
|
Sets or retrieves the current synchronization direction of data for the mobile client. You can indicate whether the client should perform normal synchronization with
This direction setting affects only user data. All mobile server data, such as awknowledgements, will still be uploaded or downloaded as appropriate. |
|
Sets flag for enabling synchronization of new publications. By default, this is set to true and all publications are synchronized. However, if you set this to false, any new subscribed publications on the server are not downloaded to the client. |
|
Sets or retrieves the synchronization priority. The default is You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored. See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information. |
|
Sets and retrieves the current transport type, which can be one of the following:
|
|
Sets or retrieves the HTTP URL of the mobile server. |
|
Set flag to switch between using streaming or files to transport synchronization data. If set to true, synchronization stores uploaded and downloaded data in a file; otherwise, data is streamed. When using files, the Note: streaming requires that the underlying client transport stack implements HTTP 1.1. Thus, if a platform does not support streaming, |
|
If |
|
Sets custom user-defined transport for synchronization, which you implement in the |
|
Initiates a manual synchronization from within the application. |
|
Add progress listener. |
|
Remove progress listener. |
|
Get the current value of encrypt database flag. |
|
Enable database encryption for new databases created during sync. |
|
dbName is database name. connObj is connection object and has to be a valid connection object for particular type of database as used in OSE plugin. For pure java sync client, it must be an instance of corresponding platform-specific database connection class: net.rim.device.api.database.Database for Blackberry client, android.database.sqlite.SQLiteDatabase for Android client, java.sql.Connection for SE client |
The following example sets the user name and password to JOHN/john
. The mobile server URL is identified as localhost:88
. And a synchronization is initiated with the sync
method.
/* set up user name and password */ String user = "JOHN"; String pwd = "john"; /* create OSESession with user John */ OSESession sess = new OSESession(user, pwd.toCharArray()); /* Identify Mobile Server URL */ sess.setURL("localhost:88"); /* Identify the progress listener, myProgressTracker */ sess.setProgress(myProgressTracker); /* Initiate Sync */ sess.sync();
The OSEProgressListener
interface enables progress updates to be trapped during synchronization.
Sync calls the progress function to report the current stage and the percent of completion of that stage. The parameters for the progress method are listed in Table 3-4:
void progress (int stage, int val);
Table 3-4 OSEProgress Method Parameters
Parameter | Description |
---|---|
|
This is set to one of the constants listed in Table 3-5. |
|
This is the percentage of completion for specific |
The names of the constants which report the synchronization progress are listed in Table 3-5.
Table 3-5 OSEProgressListener Interface Constants
Constant Name | Progress Type |
---|---|
|
States that the synchronization engine is preparing local data to be sent to the server. This includes getting locally modified data. For streaming implementations this takes a shorter amount of time. |
|
States that the synchronization engine is sending data to the network. |
|
States that the synchronization engine is receiving data from the server. |
|
States that the synchronization engine is applying the newly received data from the server to the local data stores. |
|
States that the synchronization engine has completed the synchronization process. |
|
Not supported yet. |
|
Not supported yet. |
This simple class implements the OSEProgressListener
.
class myProgressTracker implements OSEProgressListener { public void progress (int state, int val) { System.out.println( "Status: "+state+"="+ val+"%" ); } //progress }
Selective sync specifies whether a publication should be synchronized or not for the next session. Set the flag with the selectPub
method to indicate whether the publication is to be synchronized on the next execution of the sync
method. The default setting is NULL
for all publications.
Note:
Automatic synchronization selectively synchronizes only publications that contain automatic publication items.Table 3-6 lists the name and description of parameter for the selectPub
method.
Table 3-6 selectPub Parameters
Name | Description |
---|---|
|
The name of the publication which is being synchronized. If the value for the For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs". |
You can implement a custom user-defined transport for synchronization with the OSETransport
interface. Implement the following methods to connect and disconnect the connection and to open the input and output streams. These methods are used for the transport when you provide your implementation in the setUserTransport
method in the OSESession
class.
SQLite only supports sequences in a replicated environment. Sequences partitioned per client are useful for generating unique, non-overlapping values to avoid data conflicts.
Note:
For details on using sequences in Berkeley DB, see Section 2.4.1.8, "Creating Client-Side Sequences for the Downloaded Snapshot".In order to emulate sequence behavior on SQLite, the Sync Client replicates the partitioned sequence information from the server. The mobile client applications can generate unique column values from the partitioned sequence information, which is replicated for every SQLite database in the C$SEQ_CLIENTS
table.
The C$SEQ_CLIENTS
table has the following definition:
TABLE C$SEQ_CLIENTS( "NAME" VARCHAR2(30) NOT NULL, -- sequence name "CUR_VALUE" NUMBER(10,0), -- current value, set to NULL on the first sync "MAX_VALUE" NUMBER(10,0) NOT NULL, -- max value "MIN_VALUE" NUMBER(10,0) NOT NULL, -- min value "PUB_NAME" VARCHAR2(30) NOT NULL, -- publication name (for internal use) "DB_NAME" VARCHAR2(30), -- database name (for internal use) "INCREMENT_BY" NUMBER(10,0) NOT NULL, -- increment PRIMARY KEY ("NAME"))
To select the next sequence value, users can perform the following:
Select CUR_VALUE
or MIN_VALUE
if CUR_VALUE
is NULL
.
Add INCREMENT_BY
to the CUR_VALUE
.
Update the CUR_VALUE
with the CUR_VALUE
+INCREMENT_BY
for the sequence.
Example 3-1 Emulating Sequences on the Mobile Client
The following Java code example demonstrates this functionality:
/* Advance sequence value using sequence properties replicated from the * server using C$SEQ_CLIENTS table * @param seq sequence name * @return int next sequence value * @throws DatabaseException if sequence is not found. */ int advanceSequence(String seq) throws Exception { int seqNextVal = 0; Statement statement = _db.createStatement( "SELECT ifnull((cur_value+increment_by),min_value) FROM "+SEQUENCES_TABLE+" WHERE name = ?"); statement.prepare(); statement.bind(1, seq); Cursor cursor = statement.getCursor(); if(cursor.next()) { Row row = cursor.getRow(); seqNextVal = row.getInteger(0); } else { throw new Exception("Sequence not found: " + seq); } cursor.close(); statement.close(); statement = _db.createStatement( "UPDATE "+SEQUENCES_TABLE+" SET cur_value = ifnull((cur_value+increment_by),min_value) WHERE name = ?"); statement.prepare(); statement.bind(1, seq); statement.execute(); statement.close(); return seqNextVal; }
This class signals a non-recoverable error during the synchronization process. The OSEException
class constructs a clear
object. The parameters for the constructor are listed in Table 3-8, "OSEException Constructor Parameter Description":
OSEException(int errCode)
OSEException(int errCode,Object arg)
OSEException(int errCode,Object arg, Throwable cause)
OSEException(int errCode, Object arg1, Object arg2)
OSEException(int errCode, Object arg1, Object arg2, Object arg3)
OSEException(int errCode, Object [] args, Throwable cause)
Table 3-8 OSEException Constructor Parameter Description
Parameter | Description |
---|---|
|
Error codes are provided within the OSEExceptionConstants class. Error codes for synchronization are provided in the OSEExceptionConstants class. Some OSEException instances are thrown from OSE APIs. Others are used as causes of the synchronization error messages. The message handler returns an error message. For a complete list of the error messages that can be thrown in OSEException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference. |
|
Return variables for information within the error message. |
|
The cause of this throwable or NULL if the cause is nonexistent or unknown. |
OSEException class extends BaseException.The methods for getting error code, cause and message are listed in Table 3-9, "BaseException Class Public Methods".
Table 3-9 BaseException Class Public Methods
Method | Description |
---|---|
|
Returns exception error code |
|
Returns exception message |
|
Returns exception cause |
|
Returns string representation of this BaseException instance. The string contains information from the whole chain of causes if present (cause of this exception is also often instance of BaseException). For each exception in the chain, it contains error code, error message and additional diagnostic information if present. |
For a complete list of the error messages that can be thrown in the OSEException
, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.
You can initiate and monitor synchronization from a native client application. The OSE synchronization methods for the native interface are defined in ose.h
, which is located in <ORACLE_HOME
>\Mobile\Sdk\include
, and implemented in ose.dll
, which is located in the <ORACLE_HOME
>\Mobile\Sdk\bin
directory.
The following sections describe how to set up and initiate synchronization:
Section 3.1.1.2.2, "Initializing the Environment With oseOpenSession"
Section 3.1.1.2.5, "Start the Synchronization With the oseSync Method"
Section 3.1.1.2.6, "Manage What Publications Are Synchronized With oseSelectPub"
Section 3.1.1.2.7, "See Progress of Synchronization with Progress Listening"
Section 3.1.1.2.8, "Cancel a synchronization event using oseCancelSync"
Section 3.1.1.2.9, "Close the Synchronization Environment Using oseCloseSession"
Section 3.1.1.2.10, "Retrieve Synchronization Error Information with oseGetLastError"
Section 3.1.1.2.11, "Enable File-Based Synchronization through Native APIs"
Section 3.1.1.2.14, "Accessing Mobile Client Configuration Parameters"
For starting synchronization, the application should perform the following:
Invoke the oseOpenSession
method to initialize the session and its environment and resources.
Set any session options. Invoke the oseSaveUser
method to preserve the last user, URL, proxy and optionally the user password for future synchronization events.
Invoke oseSync
method to synchronize, which returns after the synchronization completes, an error occurs, or the user interrupts the process.
Synchronization progress is reported through the oseProgressFunc
interface, which is set by the oseSetProgress
method.
If synchronization failed, use the oseGetLastError
method to retrieve the error message.
When done with the session, invoke the oseCloseSession
method to close the session and release its resources.
The oseOpenSession
method initializes the synchronization environment—which is passed to each subsequent call with the oseSess
handle.
In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the oseOpenSession
method. The only exception is oseCancelSync
, which can be executed by another thread.
Note:
Every time you invoke theoseOpenSession
method, you must also clean up with oseCloseSession
method. These methods should always be called in pairs. See Section 3.1.1.2.9, "Close the Synchronization Environment Using oseCloseSession" for more information.oseError oseOpenSession(const char *user, const char *pwd, oseSess *sess);
Table 3-10 lists the oseOpenSession
parameters.
Table 3-10 oseOpenSession Parameters
Name | Description |
---|---|
|
User name for synchronization. If |
|
User password. If |
|
Pointer to a session handle into which the new session is returned. This handle cannot be |
This call initializes the oseSess
synchronization environment handle—which holds context information for the synchronization engine—and restores any session options that were saved with the last oseSaveUser
method invocation. See Section 3.1.1.2.4, "Saving User Settings With oseSaveUser" for more information on oseSaveUser
.
If successful, zero is returned; otherwise, an OSE error code is returned.
You can set certain session options explicitly with the set session methods. Every session option, except OSE_OPT_NEW_PASSWORD
, is set for the duration of the session, unless it is explicitly reset with the appropriate set session option method.
When the session is created, the initial value for each option is loaded from the following:
The ose.ini
file.
If it is not set in the ose.ini
file, the option value is loaded from the saved options in the internal OSE Meta files. The OSE Meta files save session information that was either set on the previous synchronization or set explicitly with the appropriate set session option method. New values for options set by the user, such as OSE_OPT_URL
or OSE_OPT_PROXY
, are saved in the internal OSE Meta files during next synchronization.
If not set in the ose.ini
file or saved as within the OSE Meta files, the default value is taken for each option.
Options are separated into boolean, numeric, and string options:
Boolean options are those options that can only be set to OSE_TRUE
or OSE_FALSE
.
Numeric options are set to an integer value.
String options are those options that are defined with a character string.
The following sections describe the session options and the methods that can get or set the values for these options:
Boolean and Numeric Session Options
Use the oseSetNumOption
and oseGetNumOption
methods to set and get the boolean and numeric session options.
oseError oseSetNumOption(oseSess sess, int opt, long val);
Table 3-11 lists the oseSetNumOption
parameters.
Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.
Table 3-11 oseSetNumOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 3-13 for a list of all of the options that can bet set by this method. |
|
The option value to set for the session. See Table 3-13 for potential values for this option. |
oseError oseGetNumOption(oseSess sess, int opt, long *val);
Table 3-12 lists the oseGetNumOption
parameters.
Returns zero if the option is retrieved successfully. An OSE error code is returned if an invalid option code is specified.
Table 3-12 oseGetNumOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 3-13 for a list of all of the options that can bet retrieved by this method. |
|
Pointer to a variable into which to return the option value. The pointer cannot be |
Table 3-13 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE
and OSE_FALSE
.
Table 3-13 Numeric and Boolean Session Options
Session Option | Description |
---|---|
|
Specifies the synchronization direction with one of the following numeric constants:
|
|
Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.
|
|
Transport type designates the protocol used to transfer data to and from the mobile server.
|
|
Transport direction. This is used to indicate connected or disconnected (that is, File-Based) sync.
|
|
Boolean option. Indicates whether the user synchronization password should be saved on the client, which means that it will not need to be explicitly provided for future sessions. The password is saved in an encrypted form. |
|
Boolean option. If
|
|
Synchronization priority constants:
|
|
Boolean option. Indicates whether synchronization should download a list of application and client updates that can be installed later.
Also, see the |
|
Boolean option. Indicates whether new publications can be created during synchronization.
|
|
Boolean option. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server.
|
|
Boolean option. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named The related Also, see the |
|
Boolean option. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This option is used only with connected transport (
Related |
|
Boolean read-only option. You can only retrieve the value with the Also, see the |
|
Boolean option. Indicates whether any databases newly created during synchronization should be encrypted. The encryption key for each database is either retrieved from the synchronization keystore or generated based on the user password, if not found in the keystore. Applications can define their own keys for each database before database creation with the keystore APIs.
The related You can set, get, and remove the encryption key with the |
Use the oseSetStrOption
and oseGetStrOption
methods to set and get the string session options. Every string option, except the OSE_OPT_APP_ROOT
option, defaults to NULL
if not loaded during session initialization.
oseError oseSetStrOption(oseSess sess, int opt, const char *val);
Table 3-14 lists the oseSetStrOption
parameters.
Returns zero if the option is set successfully. An OSE error code is returned if an invalid option code or an invalid value is specified.
Table 3-14 oseSetStrOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 3-16 for a list of all of the options that can bet set by this method. |
|
The option value to set for the session. See Table 3-16 for potential values for this option. |
oseGetStrOption and oseGetStrOptionNC
oseError oseGetStrOption(oseSess sess, int opt, char *val, int bufSize); oseError oseGetStrOptionNC(oseSess sess, int opt, const char **val);
The difference between the two calls is that the oseGetStrOptionNC
does not require you to allocate the buffer for the returned string. Instead, a pointer to a string is passed. The string is NULL
-terminated, which is how the length is known.
Table 3-15 lists the oseGetStrOption
parameters.
Returns zero if the option is set successfully. OSE_ERR_INVALID_STR_OPT
error is returned if an invalid option code is specified. OSE_ERR_INVALID_BUFFER
error is returned if the buffer provided is too small to store the value and the terminating NULL
character.
Table 3-15 oseGetStrOption Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Option code. See Table 3-16 for a list of all of the options that can bet retrieved by this method. |
|
For |
|
For |
|
Size of the buffer. |
Table 3-16 lists all string session options and potential values.
Table 3-16 Session String Options
Option | Option Description |
---|---|
|
Mobile server URL. |
|
HTTP proxy, if present, as |
|
New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session. |
|
Read-only option, used to retrieve the synchronization user name. |
|
Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the This password is saved in the OSE Meta files if the |
|
Root directory for internal synchronization files. By default, it is the synchronization client installation |
|
File URL used for a file-based sync. Specifies the path to the file, which can optionally prefixed by |
The oseSaveUser
method saves the last user, URL, proxy and optionally the user password for future synchronization events into an OSE Meta file. However, the password is saved only if the OSE_OPT_SAVE_PASSWORD
option is enabled. These settings are normally saved at the end of each synchronization, if changes are detected. These settings can be used for the current session or used by the oseOpenSession
method to initialize the environment when next invoked.
Returns zero if successful and OSE_ERR_INTERNAL_ERROR
if an input/output error occured during saving.
oseError oseSaveUser(oseSess sess);
Table 3-17 lists the oseSaveUser
parameters.
Returns zero if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if an input/output error occurs when saving the settings.
Table 3-17 oseSaveUser Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
This saves or overwrites the user settings into an OSE Meta file on the client side.
Note:
See Section 3.1.1.2.3, "Setting Session Options" for details on the user settings saved.Starts the synchronization process synchronously.
Returns zero if synchronization is successful. Returns OSE_ERR_INVALID_SESS
if session handle was invalid and OSE_ERR_SYNC_CANCELED
if synchronization was canceled from another thread by the oseCancelSync
method. Other OSE error codes are returned if the synchronization fails.
oseError oseSync(oseSess sess);
Table 3-18 lists the oseSync
parameters.
Selective sync allows only certain publications to be synchronized. The oseSelectPub
method selects a publication for selective sync, which specifies if it is to be synchronized on the next synchronization. Selective sync only works if you have first performed at least one synchronization for the client. Then, a selective sync for the publication occurs at the next invocation of the oseSync
method.
The application can select publications needed by repeatedly calling the oseSelectPub
method. To revert to the regular (non-selective) synchronization selection, invoke this method with NULL
as the publication name.
The default setting is for all publications to be synchronized.
oseError oseSelectPub(oseSess sess, const char *pub);
Table 3-19 lists the oseSelectPub
parameters.
Returns zero if successful. Returns the OSE_ERR_PUB_NOT_FOUND
error if the publication with the provided name was not found.
Table 3-19 oseSelectPub Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Publication name to select for the next synchronization. |
You can implement a progress callback function that is called so that you can be notified of the progress of the synchronization operations. If you create and set the progress callback method, the mobile client invokes this callback method at appropriate times while the oseSync
method is executing.
The following is the declaration of the progress callback function.
oseError (* oseProgressFunc)(void *ctx, int stage, int val);
When the oseOpenSession
invokes the method you declare in oseSetProgress
, it provides the following information as input to your method:
ctx
—A pointer to user-defined state information for the callback. This handle is a pointer to a user-defined structure. Since the oseProgressFunc
callback method is user-implemented, it should know how to process the user-defined structure. The user context structure may or may not be initialized by the application before calling the oseSetProgress
method.
stage
—The stage in the synchronization process, which is one of the following values, where these values are defined in ose.h
:
Table 3-20 Description of the Stage Values
Stage Value | Value | Description |
---|---|---|
|
0 |
No synchronization occuring. |
|
1 |
Preparing data into temporary files. This state only occurs if the |
|
2 |
Sending the data to the mobile server. |
|
3 |
Receiving data from the mobile server. |
|
4 |
Processing data from temporary file. This state only occurs if the |
val
—The percentage completed in the particular stage that synchronization is in from 0 to 100.
After you define the progress callback function, you can initialize it with the mobile client by executing the oseSetProgress
method:
oseError oseSetProgress(oseSess sess, void *ctx, oseProgressFunc pf);
You can unregister the progress callback function by executing oseSetProgress
method as follows:
oseSetProgress(oseSess, NULL, NULL);
Table 3-21 lists the oseSetProgress
parameters.
Table 3-21 oseSetProgress Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
A pointer to the session environment settings. This handle is a pointer to a user-defined structure. Since the |
|
The progress callback function. |
Cancels the synchronization operation from another thread and returns immediately without waiting for the synchronization operation to abort.
oseError oseCancelSync(oseSess sess);
Table 3-22 lists the oseCancelSync
parameters.
Returns zero, if successful. Returns OSE_ERR_INVALID_SESS
if the oseSess
session handle is invalid.
Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every oseOpenSession
, even if oseSync
has not been executed even once.
Returns zero, if successful. Returns OSE_ERR_INVALID_SESS
if the oseSess
session handle is invalid.
oseError oseCloseSession(oseSess sess);
Table 3-23 lists the oseCloseSession
parameters.
Retrieves the extended synchronization error message and code from the last call. This information contains the last OSE error info as well as any internal errors that caused the error.
oseError oseGetLastError(oseSess sess, const oseErrorDesc **errDesc);
Table 3-24 lists the oseGetLastError
parameters.
Returns zero if successful. Returns the OSE_ERR_INVALID_SESS
error if the session handle was invalid. Returns the OSE_ERR_INTERNAL_ERROR
error if a system error has occured.
Table 3-24 oseGetLastError Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. This handle can be |
|
A pointer to an |
The oseErrorDesc
structure is defined as follows:
typedef struct _oseErrorDesc { oseError code; /* error code */ const char *type; /* a string describing the type of error */ const char *msg; /* error message */ struct _oseErrorDesc *cause; /* underlying cause, if present */ } oseErrorDesc;
If the error has an underlying cause, the oseErrorDesc.cause
points to another oseErrorDesc
structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR
, which can be further defined within another oseErrorDesc
structure. If the cause is not present, oseErrorDesc.cause
is NULL
.
Note:
The memory foroseErrorDesc
structure is allocated within the mobile client and should not be freed by the application.When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when you initiate manual synchronization, then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.
To enable file-based synchronization programmatically, perform the following:
Ensure that any previous settings of the File-Based Sync properties are set to NULL
.
Initialize the session with the oseOpenSession
method providing the user name and password for the user that is initializing the synchronization.
Specify File-Based Sync by setting OSE_OPT_TRANSPORT_TYPE
to OSE_TR_TYPE_FILE
.
Specify the synchronization direction in the OSE_OPT_TRANSPORT_DIRECTION
option as follows:
OSE_TR_DIR_SEND
: Send, which creates the synchronization file.
OSE_TR_DIR_RECEIVE
: Receive, which takes in a file from the mobile server.
Set the OSE_OPT_FILE_URL
to the path and filename of the file.
If sending, the path and filename is where the mobile client saves the uploaded data for the mobile server. This file is created with the mobile client transactions destined for the mobile server.
If receiving, the path and filename where the data file that was received from the mobile server. This file is loaded and processed within the mobile client.
Provides a database connection handle from the application to use in the OSE engine, instead of the OSE engine opening its own database connection, which is the default. The connection handle is set for the duration of the session unless explicitly unset by the same call with a NULL
connection handle value.
Applications can keep open cursors while invoking synchronization. If the connection is not shared, the OSE engine needs to create its own connection and start a new exclusive transaction; however, SQLite does not support creating exclusive transactions when another connection has open cursors.
oseError oseShareConnection(oseSess sess, const char *db, void *connHdl);
Table 3-25 lists the oseShareConnection
parameters.
Returns zero, if successful. Returns OSE_ERR_PLUGIN_ERROR
if a plugin error has occured, the value of which can be retrieved with the oseGetLastError
method.
Table 3-25 oseShareConnection Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which the connection handle is provided. |
|
Valid database connection handle for a particular type of database that is used in the OSE plugin. For example, for SQLite and Berkeley DB, the connection handle should be of type |
An application can provide its own custom key to encrypt each database instead of using a key generated from the synchronization password. Subsequently, the key in the key store is used by the mobile client to open the database after it is created.
The oseSetDBKey
method sets a database encryption key provided by the application in the OSE key store for the database. Applications need to re-execute this call when they re-encrypt the database with a different key, so that OSE engine has the current key to access the database during synchronization.
For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 3-13.
oseError oseSetDBKey(oseSess sess, const char *db, const void *key, oseSize keyLen);
Table 3-26 lists the oseSetDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occured in the key store.
Table 3-26 oseSetDBKey Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which to set the key. |
|
Buffer with the provided key. |
|
Length of the provided key. |
The oseGetDBKey
method retrieves the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 3-13.
oseError oseGetDBKey(oseSess sess, const char *db, void *buf, oseSize bufSize, oseSize *retLen);
Table 3-27 lists the oseGetDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INVALID_BUFFER
error if the buffer was too small to store the key. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occurred in the key store.
Table 3-27 oseGetDBKey Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the synchronization environment across all calls for this session. Returns |
|
Database name for which to retrieve the key. |
|
Buffer to store the key. |
|
Size of the buffer that stores the key. |
|
Actual length of the key. The length will be zero if the key is not found. |
The oseRemoveDBKey
method removes the database encryption key from the OSE key store. For more details, see the description for the OSE_OPT_ENCRYPT_DATABASES
option in Table 3-13.
oseError oseRemoveDBKey(oseSess sess, const char *db);
Table 3-28 lists the oseRemoveDBKey
parameters.
Returns zero, if successful. Returns the OSE_ERR_INTERNAL_ERROR
error if the internal error occured in the key store.
Mobile Client configuration parameters are stored in ose.ini configuration file. For more information about this configuration file, see the Section A.1, "OSE.INI File Overview" of the "Mobile Client Guide".
On some platforms such as Win32, WinCE and Linux, this file can be read and modified using ascii editor. However on platforms like iOS, where all Mobile Client-related data, including ose.ini file, is stored within an application sandbox, user cannot access this file.
In addition, on iOS platform, device management is not currently supported, so ose.ini configuration parameters are not donwloaded from the mobile server.
Hence, two APIs are provided to read and modify ose.ini configuration parameters: oseSetParam and oseGetParamNC.
For more information on the supported ose.ini parameters, see Mobile Client Guide, Appendix A.
OSE_API oseError oseSetParam(const char *cat, const char *name, const char *val)
Table 3-29 lists the oseSetParam
parameters.
Set initialization parameter in ose.ini (or ose.txt) configuration file. This is a generic routine to set parameter for any sync component based on component name (category) and parameter name.
Note:
The new parameter value will only take effect when new OSE session is opened.Returns zero if successful. Returns OSE_ERR_INTENRAL_ERROR error code if ose.ini file could not be modified or saved.
Table 3-29 oseSetParam Prameters
Name | Description |
---|---|
|
Parameter category (for example, OSE, SQLITE, JAVADB, BGSYNC, NETWORK) |
|
Parameter name (for example, RESUME, DATA_DIRECTORY, etc.) |
|
Parameter value represented as string. If the given parameter already exists in ose.ini, its value will be overwritten by val. |
OSE_API oseError oseGetParamNC(const char *cat, const char *name, const char **val);
Table 3-30 lists the oseGetParamNC
parameters.
Get initialization parameter value from ose.ini (or ose.txt) configuration file. This is a generic routine to get parameter value for any sync component based on component name (category) and parameter name. The parameter value is retrieved without copying. The memory for the parameter value is stored within OSE engine and is valid until the next call to oseGetParamNC.
Returns zero if successful. Returns OSE_ERR_INTENRAL_ERROR error code if ose.ini file could not be read.
Table 3-30 oseGetParamNC Prameters
Name | Description |
---|---|
|
Parameter category (for example, OSE, SQLITE, BGSYNC, NETWORK) |
|
Parameter name (for example, RESUME, DATA_DIRECTORY, etc.) |
|
Pointer to a character pointer into which the return value cannot be NULL. If a given parameter does not exist in ose.ini, pointer pointed to by val will be set to NULL. |
The following code:
oseError e;e = oseSetParam("SQLITE", "DATA_DIRECTORY", "tmp/sqlite_db");
will set the following in ose.ini:
SQLITE.DATA_DIRECTORY=tmp/sqlite_db
The following code:
oseError e;e = oseSetParam("OSE", "RESUME", "YES");
will set the following in ose.ini:
OSE.RESUME=YES
The following code:
const char *v;oseError e;e = oseGetParamNC("SQLITE", "DATA_DIRECTORY", &v);
will retrieve the value of SQLITE.DATA_DIRECTORY parameter into the variable v.
The following sections describe how you can use the OSE .Net Synchronization APIs to build your own client synchronization initiation on mobile clients:
Note:
OCAPI Synchronization APIs for C# are no longer supported, use the APIs described in this section instead.The .Net interface for mobile client synchronization resides in the Oracle.OpenSync.OSE
namespace and is implemented in Oracle.OpenSync.dll
.
The .Net interface provides for the following functions:
Setting client-side user profiles containing data.
Starting the synchronization process.
Tracking the progress of the synchronization process.
Table 3-31 lists all enumerations and values that can be used by OSESession
APIs.
Enumeration | Members |
---|---|
Specifies the synchronization direction as follows:
|
|
Specifies the encryption type, which indicates how the data is encrypted when transfered over the network.
|
|
Transport type designates the protocol used to transfer data to and from the mobile server.
|
|
Synchronization priority:
|
|
Synchronization stage:
|
OSESession
enables setting synchronization parameters and options. This class exposes APIs to invoke and control synchronization by using the provided synchronization options.
In a multi-threaded environment, you cannot execute OSESession
methods from multiple threads. Each thread should open its own session. The only exception is CancelSync
, which can be executed by another thread.
The parameters for the constructor are listed in Table 3-32.
OSESession( ) OSESession( String user ) OSESession( String user, char[] pwd)
Table 3-32 OSESession Class Constructor
Parameter | Description |
---|---|
|
A string containing the name used for authentication by the mobile server. |
|
A character array containing the user password. |
The public methods and their parameters for the OSESession
class are listed in Table 3-33:
Table 3-33 OSESession Class Public Method Parameters
Method | Description |
---|---|
|
Attempts to cancel the synchronization process with a non-blocking call. |
|
Closes any active database connections that the session maintains. This method is called before application exits. |
|
The |
|
The The See Section 3.1.1.3.6, "Selective Synchronization" for more information. |
|
Set synchronization progress listener with the |
|
Initiates a manual synchronization from within the application. |
|
Provides database connection handle from the application to use in the OSE engine, instead of engine opening its own database connection, which is default. The connection handle is set for the duration of the session unless explicitly unset by calling Parameters include the database name and a connection handle, which has to be a valid native handle for the particular type of database that is used in the OSE plugin. For example, SQLite and Berkeley DB handle should be of native type |
The following documents the properties for the OSESession
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 3-34 lists all properties. Table 3-31 lists all enumerations.
Table 3-34 OSESession Properties
Property | Accessors | Description |
---|---|---|
|
Read-write |
Gets or sets the synchronization direction on the |
|
Read-write |
Gets or sets the encryption type on the |
|
Read-write |
Gets or sets the transport type on the |
|
Read-write |
Gets or sets the synchronization priority on the |
|
Read-write |
Boolean property. The default is The password is saved in an encrypted form. |
|
Read-write |
Boolean property. Indicates whether the next synchronization should be an automatic synchronization. The default is |
|
Read-write |
Boolean property. Indicates whether synchronization should download a list of application and client updates that can be installed later. The default is |
|
Read-write |
Boolean property. Indicates whether new publications can be created during synchronization. The default is |
|
Read-write |
Boolean property. Indicates if the synchronization is force-refresh. Ignores client changes and reloads all client data from the mobile server. The default is |
|
Read-write |
Boolean property. Indicates whether files are used to temporarily store the data either before it is sent or after it is received. If enabled, client changes are first saved into a file named The related |
|
Read-write |
Boolean property. Indicates whether the resume protocol should be used on top of the synchronization transport. To use this option, the The resume protocol is typically used for lengthy synchronization sessions over unstable network connections. It resumes sending and receiving data from the point of a network disconnect, thus avoiding the restart of synchronization from scratch. This property is used only with connected transport ( The default is Related |
|
Read-write |
Mobile server URL property. |
|
Read-write |
HTTP proxy property, if present, as |
|
Write-only |
New password provided to modify the synchronization password during the next synchronization. This option needs to be set each time the password needs to be changed for the session. |
|
Read-only |
Read-only property, used to retrieve the synchronization user name. |
|
Write-only |
Used to set the synchronization password in the current session. This overwrites the password that was originally provided to the This password is saved in the OSE Meta files if the |
|
Read-write |
Root directory for internal synchronization files. By default, it is the synchronization client installation |
/* Create the OSESession object */ oseSess = new OSESession(user, pwd != NULL ? pwd.ToCharArray() : NULL); /* Assign Session options */ if (url != NULL) oseSess.URL = url; if (f) oseSess.UseFiles = true; if (sp) oseSess.SavePassword = true; if (bResume) oseSess.UseResume = true; if (ne) oseSess.EncryptionType = EncryptionType.None; else if (ssl) oseSess.EncryptionType = EncryptionType.SSL; /* Save the session options */ if (!ns) oseSess.SaveUser(); /* Assign a progress handler named syncProgress */ oseSess.SyncProgress += new OSEProgressHandler(syncProgress); /* Perform the synchronization */ oseSess.Sync();
The following documents the properties for the OSEProgressEventArgs
class, which are used primarily in the OSEProgressHandler
interface.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Table 3-35 lists all properties.
The OSEProgressHandler
interface enables progress updates to be trapped during synchronization.
Sync calls the a registered progress handler to report the current stage and the percent of completion of that stage, which can be retrieve with the Stage
and Value
properties, as described in Table 3-34.
public delegate void OSEProgressHandler(object sender, OSEProgressEventArgs args);
Table 3-36 OSEProgressHandler Parameters
Name | Description |
---|---|
|
Sender of the event, which is set to the |
|
Progress event arguments that include |
You can implement your own progress handler by providing the same parameter declaration as in the OSEProgressHandler
declaration. The following implements a progress handler called syncProgress
, which takes in a sender and an OSEProgressEventArgs
structure. It evaluates the Stage
and the Value
of the OSEProgressEventArgs
structure when invoked by the Sync Agent.
static void syncProgress(object sender, OSEProgressEventArgs args) { if (args.Stage == SyncProgressStage.Idle) return; if (prevVal == -1) { Console.Write(args.Stage); prevVal = 0; } int dots = (args.Value - prevVal) / 2; for(int i = 0; i < dots; i++) Console.Write('.'); if (args.Value == 100) { Console.WriteLine(); prevVal = -1; } else prevVal = args.Value; }
Then, you set the progress handler by setting the SyncProgress
event, as shown below:
oseSess.SyncProgress += new OSEProgressHandler(syncProgress);
Selective sync specifies whether a publication should be synchronized or not for the next session. Provide the name of the publication with the SelectPub
method to indicate whether the publication is to be synchronized on the next execution of the Sync
method. The default setting is NULL
for all publications.
Note:
Automatic synchronization selectively synchronizes only publications that contain automatic publication items.Table 3-37 lists the name and description of parameter for the SelectPub
method.
Table 3-37 SelectPub Parameters
Name | Description |
---|---|
|
The name of the publication which is being synchronized. If the value for the For more information, see Section 2.4, "Creating Publications Using Oracle Database Mobile Server APIs". |
This class signals an error during the synchronization process.
The OSEException
read-only properties are listed in Table 3-38.
Table 3-38 OSEException Properties
Parameters | Description |
---|---|
|
Gets the exception error code. The error code can be one of the |
|
Gets the exception type name. |
|
Use the |
OSEException(int errorCode)
OSEException(int errorCode, string errorMessage)
Table 3-39 OSEException Parameter Description
Parameter | Description |
---|---|
|
The error code can be one of the |
|
A readable text message that provides extra information. |
For a complete list of the error messages in the OSEException
class, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.
The following sections describe how you can use the PhoneGap:
PhoneGap framework allows applications written in HTML/JavaScript to run on various mobile device platforms and access certain native APIs. The mobile client synchronization PhoneGap plugin enables existing or new HTML/JavaScript applications to synchronize data with the Database Mobile Server. Among several APIs provided by PhoneGap, there is a Storage API that can be used to access the synchronized data stored in the local SQLite database. For more details, see http://docs.phonegap.com/en/2.5.0/cordova_storage_storage.md.html#Storage
In addition, there is an Android sqlitePlugin which allows similar SQLite specific data access. For more details, see https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The OSE JavaScript interface provides for the following functions:
Setting client-side user profiles containing data such as user name, password, and server.
Starting the synchronization process.
Tracking the progress of the synchronization process.
For Android clients, the underlying native PhoneGap plugin implementation creates wrappers on top of the existing Java OSE API and is modeled after it. It has the follwing two jar files:
phonegap_sync_android.jar
osync_android.jar
It also has a JavaScript file osync.js.
The file locations are:
<MOBILE_HOME>\Mobile\Sdk\android\phonegap\libs\phonegap_sync_android.jar
<MOBILE_HOME>\Mobile\Sdk\android\lib\osync_android.jar
<MOBILE_HOME>\Mobile\Sdk\android\phonegap\assets\www\osync.js
The sync API is incapsulated in OSESession JavaScript class. The background sync API is exposed in BGSession class. For an example of a sync PhoneGap application for Android, please see the demo shipped with MDK under:
<MOBILE_HOME>\Mobile\Sdk\samples\sync\android\phonegap
OSESession enables setting synchronization parameters and options. This class exposes JavaScript API to invoke and control synchronization by using the provided synchronization options.
Note:
There should only be a single OSESession instance per PhoneGap application.The OSESession Class Constructors are as follows:
OSESession (success_cbk, error_cbk) OSESession (success_cbk, error_cbk, user) OSESession( success_cbk, error_cbk, user, pwd)
Table 3-40 lists all the parameters for the constructor.
Table 3-40 OSESession Class Constructor
Parameter | Description |
---|---|
A callback function that gets invoked upon successful sync completion. |
|
An error callback function that gets invoked on any error in OSE API. |
|
A string containing the name used for authentication by the mobile server. |
|
A string containing the user password. |
The public methods and their parameters for the OSESession class are listed in Table 3-41:
Table 3-41 OSESession Class Public Method Parameters
Parameter | Description |
---|---|
Attempts to cancel the synchronization process with a non-blocking call. If successful, sync calls error callback with ”Sync Canceled” error message. |
|
Closes any active database connections that the session maintains. This method is called before application exits or before a new session needs to be created (for example, when a user id is changed). |
|
|
The saveUser method saves user information, such as users specific information, and the last synchronization user id. The getUser method retrieves current synchronization client name. |
Provided the publication name, adds the publication to the list of publications to be synchronized selectively. See Section 3.1.1.1.4, "Selective Synchronization" for more information. |
|
|
Sets or retrieves the current root directory, as set in the DATA_DIRECTORY parameter, for internal synchronization and database files for the application. |
|
Sets or returns TRUE if a synchronization event is an automatic synchronization; FALSE if not. |
|
Sets or retrieves the current encryption type. Possible types can are as follows:
|
|
Set to wipe out all of the client data and replace it with server data, if true. Retrieves value of force refresh. |
|
This is used to set and get the flag for persistently saving the user password. If true, the password is saved. |
|
Allows clients to modify their password on the server. After a successful synchronization, the client's password on the server is changed to the new password. |
|
Provide or modify the mobile client password. |
|
Sets whether or not native sync progress listener is displayed. |
|
Sets or returns the current HTTP proxy, which can be the hostname or IP address of the proxy server. NULL is returned if proxy is not used. |
|
Sets or retrieves a flag that indicates whether the application client updates should be downloaded during the next synchronization. If set to FALSE, client updates are only uploaded to the server. |
|
Sets or retrieves the current synchronization direction of data for the mobile client. You can indicate whether the client should perform normal synchronization with DIR_SENDRECEIVE, where data is both uploaded and downloaded. Alternatively, if you set the direction for data to be as follows:
This direction setting affects only the user data. All mobile server data, such as acknowledgements, will still be uploaded or downloaded as appropriate. |
|
Sets or retrieves flag for enabling synchronization of new publications. By default, this is set to true and all publications are synchronized. However, if you set this to false, any new subscribed publications on the server are not downloaded to the client. |
|
Sets or retrieves the synchronization priority. The default is PRIO_DEFAULT, which is OFF. Only high priority table or rows are synchronized when set to PRIO_HIGH.You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored.For more information, see Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide. |
|
Sets or retrieves the HTTP URL of the mobile server. |
|
Sets or retrieves flag to switch between using streaming or files to transport synchronization data. If set to true, synchronization stores uploaded and downloaded data in a file; otherwise, data is streamed.When using files, the ose$in.bin file contains the data received from the server. The ose$out.bin file contains the data sent to the server. These files are located in the <mobileclient_root>\bin directory on Win32, Windows Mobile and Linux platfoms or in the directory specified by the DATA_DIRECTORY on the Android or Blackberry platforms.Note: streaming requires that the underlying client transport stack implements HTTP 1.1. Thus, if a platform does not support streaming, setUseFiles must be configured as TRUE. |
|
If setUseResume is set to TRUE, enables the resume feature, which attempts to resume sending and receiving data for a synchronization after a network failure. Requires that setUseFiles is also set to TRUE; otherwise, this method is ignored. The resume feature provides a more reliable transport for synchronizing data with minimal overhead. |
|
Initiates a manual synchronization from within the application. |
|
Get the current value of encrypt database flag. |
|
Enable database encryption for new databases created during sync. |
The following example sets the user name and password to JOHN/john. The mobile server URL is identified as localhost:88. And a synchronization is initiated with the sync method.
//* set up user name and password */ var user = "JOHN"; var pwd = "john"; //PhoneGap error callback. Prints error message on console function onError(msg) { console.log("Encountered Error: " + msg); }; //PhoneGap success callback. Prints success on console function onSuccess() { console.log("Success"); }; /* create OSESession with user John */ OSESession sess = new OSESession(onSuccess, onError, user, pwd); /* Identify Mobile Server URL */ sess.setURL("localhost:88"); /* Enable progress monitor GUI */ sess.setProgress(true); /* Initiate Sync */ sess.sync();
You can initiate and monitor synchronization from an .Net provider application. See the SQLite documentation for information on the .Net provider.
Note:
The following OCAPI synchronization APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the Section 3.1.1, "OSE Synchronization API for Applications on Mobile Clients".The following sections describe the OCAPI synchronization APIs:
You can initiate and monitor synchronization from a C or C++ client application. The OCAPI synchronization methods for the C/C++ interface are contained in ocapi.h
and ocapi.dll
, which are located in the <MOBILE_HOME>\Mobile\Sdk\include directory and <MOBILE_HOME>\Mobile\Sdk\Bin
directory respectively.
A C++ example is provided in the <MOBILE_HOME>\Mobile\Sdk\Samples\sync\win32\msync
directory. You can follow the instruction in ReadMe.txt to build the executable- SimpleSync.exe.
The following sections describe how to set up and initiate synchronization:
Section 3.1.3.1.2, "Initializing the Environment With ocSessionInit"
Section 3.1.3.1.6, "Retrieving Publication Information With ocGetPublication"
Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo"
Section 3.1.3.1.8, "Manage What Tables Are Synchronized With ocSetTableSyncFlag"
Section 3.1.3.1.10, "Start the Synchronization With the ocDoSynchronize Method"
Section 3.1.3.1.11, "See Progress of Synchronization with Progress Listening"
Section 3.1.3.1.12, "Clear the Synchronization Environment Using ocSessionTerm"
Section 3.1.3.1.13, "Retrieve Synchronization Error Message with ocGetLastError"
Section 3.1.3.1.14, "Enable File-Based Synchronization through C or C++ APIs"
For starting synchronization, the application should perform the following:
Create, memset, and initialize the ocEnv
structure.
Invoke the ocSessionInit()
method.
Set any optional fields in the ocEnv
structure, such as user name and password. If you want to preserve all optional fields set in the ocEnv
structure for future synchronization sessions, then execute the ocSaveUserInfo
method.
Optionally, you can set proxy information with the ocSetSyncOption
method or specify the synchronization type for each table with the ocSetTableSyncFlag
function.
Invoke the ocDoSynchronize()
method, which returns after the synchronization completes, an error occurs, or the user interrupts the process. While executing, the ocDoSynchronize
function invokes any callback function set in the ocEnv.fnProgress
field. The callback function must not call any blocking functions, as this process is not reentrant or threaded.
Once synchronization completes, then invoke the ocSessionTerm()
method to clear the ocEnv
data structure.
If synchronization failed, then use the ocGetLastError
function to retrieve the error message.
For an example, see the SimpleSync.cpp
sample code.
The ocSessionInit
function initializes the synchronization environment—which is contained in the ocEnv
structure or was created with ocSaveUserInfo
. For more information, see Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo".
Note:
Every time you invoke theocSessionInit
function, you must also clean up with ocSessionTerm
. These functions should always be called in pairs. See Section 3.1.3.1.12, "Clear the Synchronization Environment Using ocSessionTerm" for more information.int ocSessionInit( ocEnv env );
Table 3-42 lists the ocSessioninit
parameter and its description.
Table 3-42 ocSessionInit Parameters
Name | Description |
---|---|
|
An |
This call initializes the ocEnv
structure—which holds context information for the synchronization engine—and restores any user settings that were saved in the last ocSaveUserInfo
call, such as user name and password (See Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo"). An ocEnv
structure is passed as the input parameter. Perform the following to prepare the ocEnv
variable:
Create the ocEnv
by allocating a variable the size of ocEnv
.
Memset the ocEnv
variable before invoking the ocSessionInit
function. If you do not perform a memset
on the ocEnv
variable, then the ocSessionInit
function will not perform correctly.
Set all required fields in the ocEnv
structure before passing it to ocSessionInit
. If you want to save the user preferences for future sessions, then invoke the ocSaveUserInfo
method.
For a full description of ocEnv
, see Section 3.1.3.1.4, "ocEnv Data Structure".
The following example allocates a new ocEnv
, which is then passed into the ocSessionInit
call.
env = new ocEnv; // Reset ocenv memset( env, 0, sizeof(ocEnv) ); // init OCAPI ocError rc = ocSessionInit(env);
Two data structures—ocEnv Data Structure and ocTransportEnv Data Structure—are used for certain functions in the Mobile Sync API.
The ocEnv
data structure holds internal memory buffers and state information. Before using this structure, the application initializes it by passing it to the ocSessionInit
method.
Table 3-43 lists the field name, type, usage, and corresponding description of the ocEnv
structure parameters.
Required—If the usage is required, then you either set before calling the ocSessionInit
function or you have saved these parameters previously with the ocSaveUserInfo
function.
Optional—If the usage is optional, then optionally set after calling the ocSessionInit
function and before the ocDoSynchronize
function.
Read Only.
Table 3-43 ocEnv Structure Field Parameters
Field | Type | Usage | Description |
---|---|---|---|
|
|
Required. |
Name of the user to authenticate. This name is limited to 28 characters, because of other parts of the product. |
|
|
Required. |
User password (clear text). This name is limited to 28 characters, because of other parts of the product. |
|
|
Required. |
If set to If set to If set to |
|
|
Optional. |
If first character of this string is not NULL—in otherwords (char) 0—this string is sent to the server to change the user password; the password change is effective on the next synchronization session. |
|
|
Optional. |
If set to 1, the password is saved locally and is loaded the next time |
|
|
Optional. |
Directory to where the application will be copied. If first character is NULL, then it uses the default directory. |
|
|
Optional. |
0= OFF (default) 1= ON; Only high priority table or rows are synchronized when turned on. You can only use fast refresh with a high priority restricting predicate. If you use any other type of refresh, the high priority restricting predicate is ignored. See Section 1.2.10, "Priority-Based Replication" in the Oracle Database Mobile Server Troubleshooting and Tuning Guide for more information. |
|
|
Optional. |
If set to 0, then AES is used on the transport. If set to |
|
|
Optional. |
If set to 0 ( |
|
|
Read-only. |
Extended error code - either OS or OKAPI error code. |
|
|
Transport buffer. See Section 3.1.3.1.5, "ocTransportEnv Data Structure". |
|
|
|
Optional. |
If not NULL, points to the callback for progress listening. See Section 3.1.3.1.11, "See Progress of Synchronization with Progress Listening". |
|
|
Reserved |
|
|
|
Reserved |
|
|
|
Optional. |
Can be set to anything by the caller for context information (such as progress dialog handle, renderer object pointer, and so on. |
|
|
Reserved. |
|
|
|
Reserved. |
|
|
|
Reserved (for Wireless/Nettech only). |
|
|
|
Optional. |
If set to 1, then only push changes to the server. |
|
|
Optional. |
Set to 1 (by default), performs application deployment. If set to 0, then no applications will be received from the server. |
|
|
Optional. |
If set to 1 (default), receives any new publication created from the server since last synchronization. If set to 0, only synchronizes existing publications (useful for slow transports like wireless). |
|
|
Optional. |
Debug only. If set to 1, logs server-side insert and update row information to the publication client database. |
|
|
Optional. |
Debug only. A bitset of the following flags:
|
|
|
Caller can set to 1 on next operation. |
The environment structure contains fields that the caller can update to change the way Mobile Sync module works. The following example demonstrates how to set the fields within the ocEnv
structure.
typedef struct ocEnv_s { // User info char username[MAX_USERNAME]; // Mobile Sync Client id, limited to 28 characters char password[MAX_USERNAME]; // Mobile Sync Client password for // authentication during sync, limited to 28 chars char newPassword[MAX_USERNAME]; // resetting Mobile Sync Client password // on server side if this field is not blank short savePassword; // if set to 1, save password char appRoot[MAX_PATHNAME]; // dir path on client device for deploying files short priority; // High priority table only or not short secure; // if set to 1, data encrypted over the wire enum { OC_SENDRECEIVE = 0, // full step of synchronize OC_SENDONLY, // send phase only OC_RECEIVEONLY, // receive phase only OC_SENDTOFILE, // send into local file | pdb OC_RECEIVEFROMFILE // receive from local file | pdb }syncDirection; // synchronize direction enum { OC_BUILDIN_HTTP = 0, // Use build-in HTTP transport method OC_USER_METHOD // Use user defined transport method }trType; // type of transport ocError exError; // extra error code ocTransportEnv transportEnv; // transport control information // GUI related function entry progressProc fnProgress; // callback to track progress; this is optional // Values used for Progress Bar. If 0, progress bar won't show. long totalSendDataLen; // set by Mobile Sync API informing transport total number // of bytes to send; set before the first fnSend() is called long totalReceiveDataLen; // to be set by transport informing Mobile Sync API // total number of bytes to receive; // should be set at first fnReceive() call. void* userContext; // user defined context void* ocContext; // internal use only short logged; // internal use only long bufferSize; // send/receive buffer size, default is 0 short pushOnly; // Push only flag short syncApps; // Application deployment flag short cancel; // cancel } ocEnv;
You can configure the HTTP URL, proxy, proxy port number and other HTTP-specific transport definitions in the ocTrHttp
structure. This structure is an HTTP public structure defined in octrhttp.h
.
You access the ocTrHttp
structure from within the ocTransportEnv
data structure, which is provided as part of the ocEnv
data structure. The following demonstrates the fields within the ocTransportEnv
structure:
typedef struct ocTransportEnv_s { void* ocTrInfo; // transport internal context
The ocTrInfo
is a pointer that points to the HTTP parameters in the ocTrHttp
structure. The following code example retrieves the ocTrInfo
pointer to the HTTP parameters and then modifies the URL, proxy, and proxy port number to the input arguments:
ocTrHttp* http_params = (ocTrHttp*)(env->transportEnv.ocTrInfo); // set server_name strcpy(http_params->url, argv[3]); // set proxy strcpy(http_params->proxy, argv[4]); // set proxy port http_params->proxyPort = atoi(argv[5])
This function gets the publication name on the client from the application name. The user knows only the application name, which happens when the Packaging Wizard is used to package an application before publishing it. If the application needs the publication name in order to interact with the database, then this function is used to retrieve that name, given the application name.
ocError ocGetPublication(ocEnv* env, const char* application_name, char* buf, int buf_len);
The parameters for the ocGetPublication
function are listed in Table 3-44 below.
Table 3-44 ocGetPublication Parameters
Name | Description |
---|---|
|
Pointer to an |
|
The name of the application. |
|
The buffer where the publication name is returned. |
|
The buffer length, which must be at least 32 bytes. |
Return value of 0 indicates that the function has been executed successfully. Any other value is an error code.
The following code example demonstrates how to get the publication name.
void sync() { ocEnv env; int rc; // Clean up ocenv memset(&env 0, sizeof(env) ); // init OCAPI rc = ocSessionInit(&env); strcpy(env.username, "john"); strcpy(env.password, "john"); // We use transportEnv as HTTP paramters ocTrHttp* http_params = (ocTrHttp*)(env.transportEnv.ocTrInfo); strcpy(http_params->url, "your_host"); // Do not synchronize applicaton "Sample3" char buf[32]; rc = ocGetPublication(&env, "Sample3", buf, sizeof(buf)); rc = ocSetTableSyncFlag(&env, buf, NULL, 0); // call sync rc = ocDoSynchronize(&env); if (rc < 0) fprintf(stderr, "ocDoSynchronize failed with %d:%d\n", rc, env.exError); else printf("Synchronization compeleted\n"); // close OCAPI session rc = ocSessionTerm(&env); return 0; }
Saves user settings for the ocEnv
structure. These settings can be used for the current session or used by the ocSessionInit
function to initialize the environment when next invoked.
int ocSaveUserInfo( ocEnv *env );
Table 3-45 lists the ocSaveUserInfo
parameter and its description.
Table 3-45 ocSaveUserInfo Parameters
Name | Description |
---|---|
|
Pointer to the synchronization environment. |
This saves or overwrites the user settings into a file or database on the client side. The following information provided in the environment structure is saved:
Note:
See Section 3.1.3.1.4, "ocEnv Data Structure" or Section 3.1.3.1.5, "ocTransportEnv Data Structure" for more information.username
password
savePassword
newPassword
priority
secure
pushOnly
syncApps
syncNewPublications
If you use the HTTP default transport set in the ocTransportEnv
structure, then the following is also saved:
url
useProxy
proxy
proxyPort
For more information on how to use these fields, see Section 3.1.3.1.3, "Managing the C/C++ Data Structures".
Update the table flags for selective sync. Call this for each table to specify whether it should be synchronized (1) or not (0) for the next session. Selective sync only works if you have first performed at least one synchronization for the client. Then, set the flag so that on the next synchronization—that is, on the next invocation of the ocDoSynchronize
method—a selective sync occurs.
The default sync_flag
setting for ocSetTableSyncFlag
is TRUE (1) for all the tables; that is, all tables are flagged to be synchronized. If you want to selectively synchronize specific tables, you must first disable the default setting for all tables and then enable the synchronization for only the specific tables that you want to synchronize.
ocSetTableSyncFlag(ocEnv *env, const char* publication_name, const char* table_name, short sync_flag)
Table 3-46 lists the name and description of parameters for the ocSetTableSyncFlag
function.
Table 3-46 ocSetTableSyncFlag Parameters
Name | Description |
---|---|
|
Pointer to the synchronization environment. |
|
The name of the publication which is being synchronized. If the value for the |
|
This is the name of the snapshot. It is the same as the name of the |
|
If the |
This function allows client applications to select the way specific tables are synchronized.
Set sync_flag
for each table or each publication. If sync_flag
= 0, the table is not synchronized.
To synchronize specific tables only, you must perform the following steps:
Disable the default setting, which is set to 1 (TRUE) for all the tables.
Example:
ocSetTableSyncFlag(&env, <publication_name>,NULL,0)
Where <publication_name>
must be replaced by the actual name of your publication, and where the value NULL
is specified to mean all the tables for that publication without exception.
Enable the selective sync for specific tables.
Example:
ocSetTableSyncFlag(&env, <publication_name>,<table_name>,1)
If you are using a firewall and need to configure proxy information, perform the following before you execute the ocDoSynchronize
method:
Configure the proxy URL, IP address and/or port number through the ocSaveUserInfo
function. See Section 3.1.3.1.7, "Managing User Settings With ocSaveUserInfo" for more information.
If required, configure the proxy user name and password. To configure the proxy user name and password, use the ocSetSyncOption
and provide the following:
ocSetSyncOption( env, "HTTPUSER=<username>;HTTPPASS=<password>");
Note:
The user name and password are limited to 28 characters.Where the ocSetSyncOption
syntax is as follows:
int ocSetSyncOption(ocEnv *env, const char *str);
You can set one or more name/value pairs separated by a semi-colon in the string. The previous example shows the HTTPUSER
and HTTPPASS
name/value pairs. You can also set the URL string as follows: URL=www.myhost.com
.
Starts the synchronization process.
int ocDoSynchronize( ocEnv *env );
Table 3-47 lists the name and description of the ocDoSynchronize
parameter.
Table 3-47 ocDoSynchronize Parameters
Name | Description |
---|---|
|
Pointer to the synchronization environment. |
This starts the synchronization cycle. A round trip synchronization is activated if syncDirection
is OC_SENDRECEIVE
(default). If syncDirection
is OC_SENDONLY
or OC_RECEIVEONLY
, then the developer must implement a custom transport. If the developer wishes to upload only changes, then set pushonly
=1. You cannot only download changes under the existing synchronization architecture.
This method returns when the synchronize completes. A return value of 0 indicates that the function has been executed successfully. If an error occurred, local errors are returned by ocDoSynchronize
, which are defined in ocerror.h
. For errors returned by the server, see the ol_sync.log
error log file, which is written into the working directory of the application. Each line in the error file has the following format:
<type>, <code>, <date>, <message>
Where:
<type>
: The type of the message, which can either be set to ERROR
or SUCCESS
.
<code>
: Error code of the last operation of the synchronization.
<date>
: Date and timestamp for when the synchronization completes. This is in the format of dd/mm/yyyy hh:mm:ss
.
<message>
: A readable message text.
If you create and set the progress callback function, the mobile client invokes this callback function at different times while the ocDoSynchronize
method is executing. Create the callback function, as follows:
void myProgressProc ( void *env, int stage, int present);
When the ocDoSynchronize
invokes your myProgressProc
function, it provides the following information as input to your function:
env
—A pointer to the environment (ocEnv
structure) for the synchronization session. This provides the function to retrieve the userContext
pointer.
stage
—A number that denotes the stage in the synchronization process, which is one of the following values, where these values are defined in ocapi.h
:
Table 3-48 Description of the Stage Values
Stage Value | Description |
---|---|
|
Start of the prepare stage, which collects all internal data from the database and prepares to send the data to the server. |
|
Progress in the prepare stage. |
|
Prepare stage is completed. |
|
Starting to send the data to the server. |
|
Sending the data. |
|
Completed sending the data. |
|
Starting to receive data. |
|
Receiving data from the server. |
|
Completed receiving data from the server. |
|
Starting to process received data. |
|
Processing received data. |
|
Completed processing. Synchronization is finished. |
|
Resume synchronization is restarted. |
|
Last callback after the synchronization. |
present
—The percentage completed in the particular stage that synchronization is in from 0 to 100.
If the function is a member of a class, then it must be defined as static.
After you create the callback function, set the function pointer in the ocEnv.fnProgress
(Table 3-43) to the address of your callback function. Save this with the ocSaveUserInfo
or ocSessionInit
methods.
Clears and performs a cleanup of the synchronization environment and buffers. This function must be invoked for every ocSessionInit
, even if the ocDoSynchronize
function is not performed.
int ocSessionTerm( ocEnv *env );
Table 3-49 lists the ocSessionTerm
parameter and its description.
Table 3-49 ocSessionTerm Parameters
Name | Description |
---|---|
|
Pointer to the environment structure returned by |
De-initializes all the structures and memory created by the ocSessionInit()
call. Users must ensure that they are always called in pairs.
Retrieves the synchronization error message and code.
int ocGetLastError( ocEnv *env, char *buf, int buf_size);
Table 3-50 lists the ocGetLastError
parameters.
When you want to use file-based synchronization, you must enable file-based synchronization. Once enabled, then when you initiate manual synchronization, then the synchronization file is created. See Section 5.10, "Synchronizing to a File Using File-Base Sync" in the Oracle Database Mobile Server Administration and Deployment Guide for more details on file-based synchronization.
To enable file-based synchronization programmatically with the ocEnv
structure, perform the following:
Ensure that any previous settings of the File-Based Sync properties are set to NULL
.
Initialize the environment with the ocSessionInit
method.
Set the user name and password for the user that is initializing the synchronization.
Specify the synchronization direction and directory and filename for the synchronization file. The synchronization direction is either send, which creates the synchronization file, or receive, which takes in a file from the mobile server. These are configured in the SEND_FILE_PROP
and RECEIVE_FILE_PROP
properties with the ocSetSyncProperty
method.
When you set the SEND_FILE_PROP
property, specify the filename—including the relative or full path—where you want the mobile client to save the upload data for the mobile server. This file is created with the mobile client transactions destined for the mobile server.
When you set the RECEIVE_FILE_PROP
property, specify the filename—including the relative or full path—where the data file that was received from the mobile server. This file is loaded and processed within the mobile client.
The following code example sets the direction, filename, user name and password. Notice that the ocEnv
structure is memset to zero to ensure that if a previous direction and filename were specified, then these are invalidated for the next file-based synchronization. The SEND_FILE_PROP
property is set with the filename and direction, which tells the Sync Client to marshall the mobile client transactions that are to be uploaded to the mobile server into this file. If you were receiving a synchronization file from the mobile server, you would have set the RECEIVE_FILE_PROP
property with the location and name of this file.
Finally, the ocEnv
structure is provided to the ocDoSynchronize
method, which performs the file-based synchronization.
ocEnv env; memset(&env, 0, sizeof(ocEnv)); ocSessionInit(&env); strcpy(env.username, "S11U1"); strcpy(env.password, "manager"); ocSetSyncProperty(&env, SEND_FILE_PROP, "C:\\temp\\send1.bin"); ocDoSynchronize(&env); ocSessionTerm(&env);
For more information, refer to the Oracle Database Mobile Server API Specification.
The following APIs are used to manage automatic synchronization on the Mobile cllient:
Section 3.2.1, "OSE APIs for Managing Automatic Synchronization"
Section 3.2.2, "OCAPI APIs for Retrieving Status on Automatic Synchronization"
Section 3.2.3, "OCAPI Notification APIs for the Automatic Synchronization Cycle Status"
Note:
Use the OSE classes for all new application development for your mobile clients. These are the classes that will be supported for the future.Automatic synchronization is enabled by default if a publication is enabled for automated synchronization. However, you may programmatically turn on and off automatic synchronization on the mobile client using the Sync Control API.
Use the start or stop methods to start or stop the Sync Agent. The user may want to stop the Sync Agent for many reasons, such as aborting an automatic synchronization that may be running longer than desired, freeing up system resources, or de-fragmenting or backing up a client database.
Note:
There is also a GUI for starting, stopping the automatic synchronization process from the mobile server. See Section 5.5.2, "Start, Stop, or Get Status for Automatic Synchronization" in the Oracle Database Mobile Server Administration and Deployment Guide for more details.The following are the different methods of managing automatic synchronization and the Sync Agent:
Pause/Resume—Pause and resume all Sync Agent activities without stopping the process or freeing any resources, which would occur if you stopped or disabled the Sync Agent. Pause and resume are the most efficient method for suspending the Sync Agent and all automatic synchronization events, since it does not stop the process or free any resources.
By default, if you are using the mSync GUI or sync API to initiate a manual synchronization, the underlying code pauses and resumes the automatic synchronization for you, as described below:
Pause the automatic synchronization with the Sync Control API.
Initiate the manual synchronization with the programmatic API.
Resume the automatic synchronization with the Sync Control API.
In some circumstances pausing syncagent might not be immediate if syncagent is currently running automatic synchronization task and cancellation cannot occur in the moment for various reasons. If syncagent cannot pause and you want the manual synchronization to start immediately, you can kill syncagent (for native clients). This can be done either by calling API in program or forcibly ending it with autosync.exe manually on Windows or with autosync manually on Linux.
To kill syncagent by calling API, you can call bgControlAgent (bgSess, BG_CTRL_STOP, BG_CTRL_OPT_TERMINATE) in C, BGSession.kill() in java.
To kill syncagent with autosync.exe on Windows or autosync on Linux, you can try to stop syncagent and it takes time, then the "Stop" button will change to "End" and you can kill it by pressing this button. Or the process syncagent.exe on Windows or syncagent on Linux can be manually terminated. After the manual synchronization is finished successfully, syncagent is started regardless whether it was running before or not. If the manual synchronization fails, syncagent is resumed - that is, it is only started if it was running before manual synchronization.
Start/Stop—Stop the Sync Agent, which includes stopping the process and freeing all resources, until a start operation is executed or the client is restarted. If the start operation is not executed, the Sync Agent is automatically resumed when the client restarts.
Enable/Disable—Disabling the Sync Agent stops the Sync Agent until an enable operation is executed. Even restarting the client will not re-enable the Sync Agent. Thus, in a disabled state, no automatic synchronization events will occur.
The following control APIs can be used to manage automatic synchronization:
Section 3.2.1.1, "JAVA APIs for the Sync Agent and Automatic Synchronization"
Section 3.2.1.2, "Native APIs for the Sync Agent and Automatic Synchronization"
Section 3.2.1.3, "The .Net APIs for the Sync Agent and Automatic Synchronization"
Section 3.2.1.5, "JavaScript APIs for the Sync Agent and Automatic Synchronization in PhoneGap"
The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Note:
For more details on these classes, refer to the Oracle Database Mobile Server JavaDoc.Once automatic synchronization for the mobile client is enabled, you can manage it either locally through the Sync Agent APIs or remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is started, Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The Java interface for controlling the Sync Agent and automatic synchronization resides in the oracle.opensync.syncagent
package.
The Java interface provides for the following functions:
Tracking the progress of the automatic synchronization process.
Retrieve the status of the Sync Agent.
Specify custom handlers for events that occur in automatic synchronization.
The following are the classes and interface for the Java API for controlling the Sync Agent and automatic synchronization:
BGSession
Class
BGAgentStatus
Class
BGSyncStatus
Class
BGMessageHandler
Interface
BGSession
is the main class for controlling automatic synchronization through the Sync Agent, as follows:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
Note:
In a multi-threaded environment a singleBGSession
should not be used from multiple threads. Each thread should open its own session.BGSession( )
The public methods and their parameters for the BGSession
class are listed in Table 3-51:
Table 3-51 BGSession Class Public Method Parameters
Method | Description |
---|---|
|
Adds or removes a custom message handler to the Sync Agent. See Section 3.2.1.1.5, "BGMessageHandler Interface" for more information. |
|
Returns |
|
Closes the session and release all the resources used by the session. |
|
|
|
Retrieves the current Sync Agent status. See Section 3.2.1.1.3, "BGAgentStatus Object" for more details on the status information returned. |
|
Retrieves the current Sync Agent status code, which are described in Table 3-54, "Sync Agent Status Codes". |
|
Get current status of automatic synchronization managed by the Sync Agent. See Table 3-55 for more details on the status information returned. |
|
Pauses the Sync Agent. If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the |
|
Resumes the Sync Agent. If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the |
|
Starts up the Sync Agent UI. |
|
Start the Sync Agent. If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the |
|
Stop the Sync Agent. If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the |
|
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
Returns |
|
If sync agent is in DEFUNCT state, retrieve the error information that caused the bad internal state. See Table 3-54, "Sync Agent Status Codes" for description of DEFUNCT. |
The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:
// Create the BGSession object BGSession sess = new BGSession(); try { //Start the Sync Agent, which enables all automatic synchronization //events sess.start(); //Wait until the Sync Agent successfully starts sess.waitForStatus(BGAgentStatus.RUNNING); //Retrieve the status of the Sync Agent BGAgentStatus s = sess.getAgentStatus(); //Print out the user that is using automatic synchronization System.out.println("User name: " + s.clientId); //Add a message handler sess.addMessageHandler(new myMessageHandler()); ... } finally { //When finished, close the session to release all resources sess.close(); }
The BGAgentStatus
object represents the current status of the Sync Agent.
The methods for the BGAgentStatus
are listed in Table 3-52.
Table 3-52 BGAgentStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given status code. When you provide one of the status codes shown in Table 3-54, the appropriate name is returned. Translation dependent on the device language settings |
BGAgentStatus
provides status information on the Sync Agent. Table 3-53 lists and describes the status information fields within the BGAgentStatus
class.
Table 3-53 BGAgentStatus Class Fields
Parameters | Description |
---|---|
|
The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process. |
|
Remaining percentage of battery life, if relevant. |
|
Sync user name. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Network bandwidth in bits per second. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-54, "Sync Agent Status Codes". |
The BGAgentStatus
object defines the Sync Agent status codes, which are as follows:
Table 3-54 Sync Agent Status Codes
Status Code | Status Name | Description |
---|---|---|
0 |
|
Sync Agent application is not running. |
1 |
|
Sync Agent is in the process of starting. |
2 |
|
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
3 |
|
Sync Agent is in the process of being paused. |
4 |
|
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
5 |
|
Sync Agent is in the process of resuming. |
6 |
|
Sync Agent is in the process of stopping. |
7 |
|
Sync Agent encountered fatal error and is in a bad internal state. Sync Agent's environment needs to be cleaned up and restarted. |
The following provides an example of retrieving and processing the Sync Agent status:
/* retrieve the Sync Agent status */ BGAgentStatus as = bgSess.getAgentStatus(); /* Print Sync Agent status */ System.out.println("Agent Status: " + BGAgentStatus.statusName(as.statusCode)); if (as.statusCode == BGAgentStatus.STOPPED) return; /* Identify the client id, process id and name */ System.out.println("Client ID: " + as.clientId); System.out.println("Process Name: " + as.appName); System.out.println("Process ID: " + as.processId); /* network name and speed */ if (as.networkSpeed > 0) { System.out.println("Network Name: " + as.networkName); System.out.println("Network Speed: " + as.networkSpeed + " bps"); } else System.out.println("Network is not present"); /* battery power */ if (as.batteryPower > 0) System.out.println("Battery Power: " + as.batteryPower + "%"); else System.out.println("Battery is not present");
Current status of automatic synchronization. If automatic synchronization is in progress, startTime
will have a non-zero value and endTime
will be zero.
BGSyncStatus
provides status information on automatic synchronization in the fields listed in Table 3-55.
Table 3-55 BGSyncStatus Class Fields
Parameters | Description |
---|---|
|
End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run. |
|
Exception object thrown during the last synchronization. Returns |
|
Priority of the current or last synchronization. |
|
Progress stage of synchronization if it is in progress. |
|
Progress value in percentage of synchronization, if it is in progress. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown. |
The following provides an example of retrieving and processing the synchronization status:
/* Retrieve the synchronization status */ BGSyncStatus ss = bgSess.getSyncStatus(); /* start time */ if (ss.startTime == 0) return; System.out.println("Sync Started: " + time2str(ss.startTime)); /* end time */ if (ss.endTime != 0) System.out.println("Sync Finished: " + time2str(ss.endTime)); /* number of publications synchronized */ if (ss.pubs != NULL && ss.pubs.length != 0) { System.out.print("Publications synced: "); for(int i = 0; i < ss.pubs.length; i++) { System.out.print(ss.pubs[i]); if (i == ss.pubs.length - 1) System.out.println(); else System.out.print(", "); } } /* synchronization priority */ System.out.println("Sync Priority: " + (ss.prio == OSESession.PRIO_HIGH ? "High" : "Normal")); /* synchronization result */ System.out.print("Sync Result: "); if (ss.lastError == NULL) System.out.println("Success"); else System.out.println("Failure: " + ss.lastError.toString());
The BGMessageHandler
interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.
Sync calls the handleLogMessage
method with a parameter message of type LogMessage
to report the current state and any errors for the Sync Agent or automatic synchronization. Within the handleLogMessage
method, you can perform the appropriate action for the errors returned in the LogMessage
structure.
For a complete description of the LogMessage
class, see Section 3.2.1.1.6, "LogMessage Class".
This example demonstrates how to implement the BGMessageHandler
.
class myMessageHandler implements BGMessageHandler; { public void handleLogMessage(message) { private PrintStream ps = new PrintStream(new FileOutputStream(FILE_NAME, false)); ps.println("Time: " + new Date(message.time)); ps.println("Type: " + (message.type == LogMessage.INFO ? "INFO" : (message.type == LogMessage.WARNING ? "WARNING" : "ERROR"))); ps.println("Id: " + message.id); if (message.text != NULL) ps.println("Text: " + message.text); if (message.cause != NULL) ps.println("Cause: " + message.cause); } }
The LogMessage
class contains error message information passed to handlers when an event occurs within the application. It exists in the oracle.opensync.util
package.
Name | Description |
---|---|
|
For error messages, optional cause of the error, which can be If the error has an underlying cause, the |
|
Error message number. |
|
Application-specific message number. |
|
Informational message number. |
|
|
|
Name of the application that created the message. |
|
Message text. |
|
Message creation time. Number in milliseconds since the epoch. |
|
Message type: |
|
Warning message. |
The following demonstrates how to print out the error information in the LogMessage
class:
private void printMsg(PrintStream ps, LogMessage m) { ps.println("Time: " + new Date(m.time)); ps.println("Type: " + (m.type == LogMessage.INFO ? "INFO" : (m.type == LogMessage.WARNING ? "WARNING" : "ERROR"))); ps.println("Id: " + m.id); if (m.text != NULL) ps.println("Text: " + m.text); if (m.cause != NULL) ps.println("Cause: " + m.cause); ps.println();}
This class signals a non-recoverable error during the synchronization process. The BGException()
class constructs a clear
object. The parameters for the constructor are listed in Table 3-57:
BGException(int errCode)
BGException(int errCode, java.lang.Object arg)
BGException(int errCode, java.lang.Object[] args, java.lang.Throwable cause)
BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2)
BGException(int errCode, java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3)
BGException(int errCode, java.lang.Object arg, java.lang.Throwable cause)
BGException(int errCode, java.lang.Throwable cause)
Table 3-57 BGException Constructor Parameter Description
Parameter | Description |
---|---|
|
Error codes are provided within the The message handler returns an error message. For a complete list of the error messages that can be thrown in |
|
Return variables for information within the error message. |
|
The cause of this throwable or NULL if the cause is nonexistent or unknown. |
BGException class extends BaseException class. The methods for getting cause and message are listed in Table 3-9, "BaseException Class Public Methods".
For a complete list of the error messages that can be thrown in the BGException, see "Exception Error Codes and Messages" in the Oracle Database Mobile Server Message Reference.
The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The native interface for controlling the Sync Agent and automatic synchronization are defined in the <ORACLE_HOME
>\Mobile\Sdk\include\bgsync.h
file and implemented in <ORACLE_HOME
>\Mobile\Sdk\bin\bgsync.dll
.
The native interface provides for the following functions:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
The bgOpenSession
method initializes the automatic synchronization environment—which is passed to each subsequent call with the bgSess
handle.
In a multi-threaded environment, you cannot concurrently use a session from multiple threads, even with the same user. Instead, each thread should open its own session with the bgOpenSession
method.
Note:
Every time you invoke thebgOpenSession
method, you must also clean up with bgCloseSession
method. These methods should always be called in pairs. See Section 3.2.1.2.6, "Close the Synchronization Environment" for more information.bgError bgOpenSession(bgSess *sess);
Table 3-58 lists the bgOpenSession
parameters.
Table 3-58 bgOpenSession Parameters
Name | Description |
---|---|
|
Pointer to a session handle into which the new session is returned. Returns |
This call initializes the bgSess
automatic synchronization environment handle—which holds context information for the synchronization engine.
Returns zero if successful. Returns BG_ERR_INTERNAL
if a system error has occured.
You can retrieve the status of automatic synchronization events or of the Sync Agent. The following sections describe the methods for retrieving the status:
Get the Sync Agent operational status with the bgGetAgentStatus
method.
bgError bgGetAgentStatus(bgSess sess, bgAgentStatus *s);
Table 3-59 lists the bgGetAgentStatus
parameters.
Table 3-59 bgGetAgentStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Pointer to the Sync Agent status structure in which the status is returned. This pointer cannot be |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
The bgAgentStatus
structure provides status information on the Sync Agent.
typedef struct _bgAgentStatus { ose1B statusCode; oseBool isExternal; oseU2B _reserved; /**< for alignment */ const char *clientId; const char *processName; const char *networkName; ose4B processId; ose4B networkSpeed; ose4B batteryPower; } bgAgentStatus;
Table 3-60 lists and describes the status information fields.
Table 3-60 bgAgentStatus Fields
Parameters | Description |
---|---|
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-61. |
|
A boolean value that if |
|
Sync user name. |
|
Name of the process within which the Sync Agent is currently running. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Network bandwidth in bits per second. |
|
Remaining percentage of battery life, if relevant. |
Table 3-61 lists the Sync Agent status codes:
Table 3-61 Sync Agent Status Codes
Code | Status Name | Description |
---|---|---|
0 |
|
Sync Agent application is not running. |
1 |
|
Sync Agent is in the process of starting. |
2 |
|
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
3 |
|
Sync Agent is in the process of being paused. |
4 |
|
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
5 |
|
Sync Agent is in the process of resuming. |
6 |
|
Sync Agent is in the process of stopping. |
Retrieve Status of the Current Automatic Synchronization Event
Get the current status of the automatic synchronization event within the Sync Agent with the bgGetSyncStatus
method.
bgError bgGetSyncStatus(bgSess sess, bgSyncStatus *s);
Table 3-62 lists the bgGetSyncStatus
parameters.
Table 3-62 bgGetSyncStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Pointer to the synchronization status structure in which the status is returned. This pointer cannot be |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
The bgSyncStatus
structure provides status information on a current or the last automatic synchronization event in the Sync Agent.
typedef struct _bgSyncStatus { oseSize pubCnt; const char **pubs; osePrio prio; oseU1B _reserved[3]; /**< for alignment */ ose8B startTime; ose8B endTime; oseError res; const char *errMsg; const char *stateName; ose2B state; ose2B progress; } bgSyncStatus;
Table 3-63 describes the fields in bgSyncStatus
.
Table 3-63 bgSyncStatus Fields
Parameters | Description |
---|---|
|
Number of publications synchronized. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Priority of the current or last synchronization. |
|
Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown. |
|
End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run. |
|
Last synchronization error code. Returns zero if the last synchronization was successful or no synchronization has completed yet. |
|
Last synchronization error message or |
|
Current synchronization stage name. |
|
Current synchronization stage Returns |
|
Progress value in percentage of synchronization, if it is in progress. |
You can issue control commands to the Sync Agent with the bgControlAgent
method. This call returns immediately and does not wait for completion of command execution. Use the bgWaitForStatus
method to wait until the Sync Agent reaches a certain status.
Issue Sync Agent Control Commands
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_COMMAND
if the control command code is invalid. Returns BG_ERR_CANNOT_ACCEPT_CTRL
if the Sync Agent is not able to execute the provided command in its current state.
bgError bgControlAgent(bgSess sess, int ctrl, int opt);
Table 3-64 lists the bgControlAgent
parameters.
Table 3-64 bgControlAgent Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Sync Agent control command codes, which are listed in Table 3-65. |
|
options for given command |
Table 3-65 lists the Sync Agent control command codes and options.
Table 3-65 Sync Agent Control Command Codes
Name | Description | Option Value |
---|---|---|
|
Start the Sync Agent. If the agent is running, pending or resume pending, this command has no effect. If the Sync Agent is paused, this command resumes the agent. |
By default, this starts the Sync Agent within a separate process named This is the default for iOS clients. |
|
Stop the Sync Agent. If the agent is stopped or stop pending, this command has no effect. |
By default, stops the Sync Agent gracefully. However, if you set the option to |
|
Pause the Sync Agent. If the agent is paused or pause pending, this command has no effect. |
No options available. |
|
Resume the Sync Agent. If the agent is running, start pending, or resume pending, this command has no effect. |
No options available. |
Wait for Specific Sync Agent Status
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
This method is often used to wait for the Sync Agent to start. For example, the following code shows starting the Sync Agent and then waiting until the Sync Agent is up and running:
bgSess sess; bgOpenSession(&sess); bgControlAgent(sess, BG_CTRL_START, 0); bgWaitForStatus(sess, BG_STATUS_RUNNING);
bgError bgWaitForStatus(bgSess sess, int statusCode, long timeOut);
Table 3-66 lists the bgWaitForStatus
parameters.
Table 3-66 bgWaitForStatus Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
The status can be one of the following: |
|
The |
Returns zero if the agent has reached specified status. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_WAIT_TIMEOUT
if the timeout has expired. Returns BG_ERR_INVALID_WAIT_STATUS
if the status code is invalid. Other errors may also be returned.
You can set certain session parameters explicitly with the set session methods. The new parameter value takes effect only after the Sync Agent is restarted. When the session is created, the initial value for each option is loaded from the ose.ini
file.
Options are separated into boolean and numeric parameters:
Boolean options are those options that can only be set to OSE_TRUE
or OSE_FALSE
.
Numeric options are set to an integer value.
Use the bgSetNumParam
and bgGetNumParam
methods to set and get the boolean and numeric session options. The bgSetNumParam
method sets a parameter in the ose.ini
file.
bgError bgSetNumParam(bgSess sess, int param, long val);
Table 3-67 lists the bgSetNumParam
parameters.
Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_PARAM
if an invalid parameter code is specified. Returns BG_ERR_INTERNAL
if a system error has occured. Other errors may also be returned.
Table 3-67 bgSetNumParam Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Parameter code. See Table 3-13 for a list of all of the options that can bet set by this method. |
|
The parameter value to set. See Table 3-13 for potential values for this option. |
bgError bgGetNumParam(bgSess sess, int param, long *val);
Table 3-68 lists the bgGetNumParam
parameters.
Returns zero if the option is retrieved successfully. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INVALID_PARAM
if an invalid parameter code is specified. Returns BG_ERR_INTERNAL
if a system error has occured.
Table 3-68 bgGetNumParam Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
Param code. See Table 3-69 for a list of all of the options that can bet retrieved by this method. |
|
Pointer to a variable into which to return the parameter value. The pointer cannot be |
Table 3-69 lists all boolean and numeric synchronization options and potential values. For all boolean options, the value can only be either OSE_TRUE
or OSE_FALSE
.
Table 3-69 Numeric and Boolean Session Options
Session Option | Description |
---|---|
|
Boolean parameter. If Refers to the |
|
Maximum number of log files to keep in the |
|
Maximum log file size in bytes. On Windows 32 and Linux, the default is 1 MB. On Windows CE, the default is 128 KB. Refers to the |
|
Time interval in milliseconds for the network manager to wait before evaluating the network state in absence of notifications. The network manager evaluates the network when a notification is received or the interval expires. The network is also evaluated periodically after each period of the said interval. The default is 10 minutes (600000 milliseconds). Refers to the |
Clears and performs a cleanup of the synchronization environment and resources. This function must be invoked for every bgOpenSession
.
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid.
bgError bgCloseSession(bgSess sess);
Table 3-70 lists the bgCloseSession
parameters.
You can create a callback function that is called when Sync Agent messages are generated, which traps automatic synchronization messages and error data. You register or unregister this callback function with the bgAddMsgCallback
or bgRemoveMsgCallback
methods.
Register the Callback Function
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occured.
bgError bgAddMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);
Table 3-71 lists the bgAddMsgCallback
parameters.
Table 3-71 bgAddMsgCallback Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
A user-defined structure that contains the session environment settings. Since the |
|
The callback function handle. |
The Sync Agent invokes the callback function with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the callback method, you can perform the appropriate action for the errors returned.
The message callback function is declared as follows:
typedef void (* bgMsgCallback)(bgUserCtx ctx, const bgMsg *msg);
Table 3-72 lists the bgMsgCallback
parameters.
Table 3-72 bgMsgCallback Parameters
Name | Description |
---|---|
|
A user-defined structure that contains the session environment settings. Since the |
|
Pointer for the message structure that reports on the current state and any errors for the Sync Agent or automatic synchronization. |
The bgMsg
structure contains error message information passed to handlers when an event occurs within the Sync Agent or automatic synchronization.
Note:
The memory forbgMsg
structure is allocated within the mobile client and should not be freed by the application.typedef struct _bgMsg { ose8B time; ose4B type; ose4B id; const char *txt; const bgErrorDesc *cause; } bgMsg;
Table 3-73 describes the fields of bgMsg
.
Name | Description |
---|---|
|
Message creation time. Number in milliseconds since the epoch. |
|
Message type: |
|
Application-specific message number. |
|
Message text. |
|
For error messages, optional cause of the error, which can be If the error has an underlying cause, the |
Unregister the Callback Function
Remove the message callback function from the Sync Agent, after which it will no longer be invoked.
Returns zero if successful. Returns BG_ERR_INVALID_SESSION
if the session handle is invalid. Returns BG_ERR_INTERNAL
if a system error has occurred.
bgError bgRemoveMsgCallback(bgSess sess, bgUserCtx ctx, bgMsgCallback cb);
Table 3-74 lists the bgRemoveMsgCallback
parameters.
Table 3-74 bgRemoveMsgCallback Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. Returns |
|
A user-defined structure that contains the session environment settings. |
|
The callback function handle. |
Retrieves the last error of a call to one of the automatic synchronization APIs.
bgError bgGetLastError(bgSess sess, const bgErrorDesc **errDesc);
Table 3-75 lists the bgGetLastError
parameters.
Returns zero if successful. Returns the BG_ERR_INVALID_SESS
error if the session handle was invalid. Returns the BG_ERR_INTERNAL
error if a system error has occured.
Table 3-75 bgGetLastError Parameters
Name | Description |
---|---|
|
Session pointer to a session handle, which contains the automatic synchronization environment across all calls for this session. This handle can be |
|
A pointer to an |
The bgErrorDesc
structure is a typedef for oseErrorDesc
, which is defined as follows:
typedef struct _oseErrorDesc { oseError code; /* error code */ const char *type; /* a string describing the type of error */ const char *msg; /* error message */ struct _oseErrorDesc *cause; /* underlying cause, if present */ } oseErrorDesc;
If the error has an underlying cause, the oseErrorDesc.cause
points to another oseErrorDesc
structure, which in turn can have its own cause, and so on. This is useful if the OSE call returns an OSE_ERR_INTERNAL_ERROR
, which can be further defined within another oseErrorDesc
structure. If the cause is not present, oseErrorDesc.cause
is NULL
.
Note:
The memory foroseErrorDesc
structure is allocated within mobile server and should not be freed by the application.The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Note:
OCAPI C# Sync Control APIs are no longer supported, use the APIs described in this section instead.Once automatic synchronization for the mobile client is enabled, you can manage it locally through the Sync Agent APIs and remotely through the Mobile Manager UI controls. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is paused, the Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The .Net interface for controlling the Sync Agent and automatic synchronization resides in the Oracle.OpenSync.SyncAgent
namespace. The .Net APIs are implemented in Oracle.OpenSync.dll
.
The .Net interface provides for the following functions:
Controlling the Sync Agent.
Retrieve the status of the Sync Agent and automatic synchronization events.
Specify custom handlers for events that occur in automatic synchronization.
The following are the classes and interface for the .Net API for controlling the Sync Agent and automatic synchronization:
BGStatusCode
Enumeration
BGSession
Class
BGAgentStatus
Class
BGSyncStatus
Class
BGMessageType
Enumeration
BGMessageHandler
Interface
The BGStatusCode
enumeration specifies the Sync Agent status codes.
public enum BGStatusCode { Stopped = 0, StartPending, Running, PausePending, Paused, ResumePending, StopPending }
Table 3-76 provides more information about these codes.
Table 3-76 Sync Agent Status Codes
Status Name | Value | Description |
---|---|---|
|
0 |
Sync Agent application is not running. |
|
1 |
Sync Agent is in the process of starting. |
|
2 |
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
|
3 |
Sync Agent is in the process of being paused. |
|
4 |
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
|
5 |
Sync Agent is in the process of resuming. |
|
6 |
Sync Agent is in the process of stopping. |
BGSession
is the main class for controlling automatic synchronization through the Sync Agent, as follows:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Specify message handlers for retrieving information about automatic synchronization events.
Note:
In a multi-threaded environment a singleBGSession
should not be used from multiple threads. Each thread should open its own session.The following documents the properties for the BGSession
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 3-77 lists all BGSession
properties. Section 3.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.
Table 3-77 BGSession Properties
Property | Description |
---|---|
|
Gets the Sync Agent status code from the |
|
Boolean property that gets or sets to |
BGSession( )
The public methods and their parameters for the BGSession
class are listed in Table 3-78:
Table 3-78 BGSession Class Public Method Parameters
Method | Description |
---|---|
|
Start the Sync Agent. If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the |
|
Same as |
|
Pauses the Sync Agent. If the agent is already paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the |
|
Resumes the Sync Agent. If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the |
|
Stop the Sync Agent. If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the |
|
Forcefully terminate the Sync Agent process instead of stopping it gracefully. Use this option as a last resort if the |
|
Closes the session and release all the resources used by the session. |
|
Retrieves the current Sync Agent status. See Section 3.2.1.3.4, "BGAgentStatus Object" for more details on the status information returned. |
|
Get current status of automatic synchronization managed by the Sync Agent. See Table 3-82 for more details on the status information returned. |
|
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
Returns |
The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:
// Create the BGSession object using(BGsession sess = new BGSession()) { //Start the Sync Agent, which enables all automatic synchronization events sess.Start(); //Wait until the Sync Agent successfully starts sess.WaitForStatus(BGAgentStatus.RUNNING); //Retrieve the status of the Sync Agent BGAgentStatus s = sess.GetAgentStatus(); //Print out the user that is using automatic synchronization Console.WriteLine("User name: " + s.clientId); //Add a message handler sess.MessageReceived += new BGMessageHandler(myHandler); ... } //When finished, close the session to release all resources sess.Close();
The BGAgentStatus
object represents the current status of the Sync Agent.
The methods for the BGAgentStatus
are listed in Table 3-79.
Table 3-79 BGAgentStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given status code. When you provide one of the status codes shown in Table 3-76, the appropriate name is returned. Translation dependent on the device language settings |
BGAgentStatus
provides status information on the Sync Agent. Table 3-80 lists and describes the status information fields within the BGAgentStatus
class.
Table 3-80 BGAgentStatus Class Fields
Parameters | Description |
---|---|
|
The name of the application or process that is executing the Sync Agent. On some platforms, such as Android, it is possible to execute the Sync Agent within an application process. |
|
Remaining percentage of battery life, if relevant. |
|
Sync user name. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Network bandwidth in bits per second. |
|
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-76. |
The following provides an example of retrieving and processing the Sync Agent status:
BGAgentStatus ags = bgSess.GetAgentStatus(); Console.WriteLine("Agent Status: " + BGAgentStatus.GetStatusName(ags.StatusCode)); if (ags.StatusCode == BGStatusCode.Stopped) return; Console.WriteLine("Client ID: " + ags.ClientId); Console.WriteLine("Process Name: " + ags.AppName); Console.WriteLine("Process ID: " + ags.ProcessId); if (ags.NetworkSpeed > 0) { Console.WriteLine("Network Name: " + ags.NetworkName); Console.WriteLine("Network Speed: " + ags.NetworkSpeed + " bps"); } else Console.WriteLine("Network is not present"); if (ags.BatteryPower > 0) Console.WriteLine("Battery Power: " + ags.BatteryPower + "%"); else Console.WriteLine("Battery is not present");
The BGSyncStatus
object provides status information on a current or the last automatic synchronization event in the Sync Agent.
The methods for the BGSyncStatus
are listed in Table 3-81.
Table 3-81 BGSyncStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given sync status code. When you provide one of the status codes shown in Table 3-76, the appropriate name is returned. Translation dependent on the device language settings |
BGSyncStatus
provides status information on automatic synchronization in the fields listed in Table 3-82.
Table 3-82 BGSyncStatus Class Fields
Parameters | Description |
---|---|
|
End time of the last synchronization. |
|
Exception object thrown during the last synchronization. Returns |
|
Priority of the current or last synchronization. |
|
Progress stage of synchronization if it is in progress. |
|
Progress value in percentage of synchronization, if it is in progress. |
|
Array of names of publications synchronized currently or during last synchronization. |
|
Start time of the last synchronization. |
The following documents the properties for the BGSyncStatus
class.
Read-write properties read or write the value of a field with get
and set
accessors.
Read-only properties read the value of a field with the get
accessor.
Write-only properties set the value of a field with the set
accessor.
Boolean properties get or set the value of a field to either true or false.
Table 3-83 lists all BGSyncStatus
properties. Section 3.2.1.3.2, "BGStatusCode Enumeration" lists all enumerations.
Table 3-83 BGSyncStatus Properties
Property | Description |
---|---|
|
Read-only boolean property. If an automatic synchronizatoin has already occured, |
|
Read-only boolean property. If automatic synchronization is in progress, |
The following provides an example of retrieving and processing the synchronization status:
BGSyncStatus ss = bgSess.GetSyncStatus(); if (!ss.SyncOccured) return; Console.WriteLine(); Console.WriteLine("Sync Started: " + dt2str(ss.StartTime)); if (!ss.SyncInProgress) Console.WriteLine("Sync Finished: " + dt2str(ss.EndTime)); if (ss.Pubs != NULL && ss.Pubs.Length != 0) { Console.Write("Publications synced: "); for(int i = 0; i < ss.Pubs.Length; i++) { Console.Write(ss.Pubs[i]); if (i == ss.Pubs.Length - 1) Console.WriteLine(); else Console.Write(", "); } } Console.WriteLine("Sync Priority: " + ss.Prio.ToString()); Console.Write("Sync Result: "); if (ss.LastError == NULL) Console.WriteLine("Success"); else Console.WriteLine("Failure: " + ss.LastError.ToString()); Console.WriteLine();
The BGMessageHandler
interface enables the Sync Agent and automatic synchronization message and error data to be trapped during synchronization.
The message handler is defined as follows:
public delegate void BGMessageHandler(object sender, BGMsgEventArgs args);
You can implement a callback function with the same input parameters as the BGMessageHandler
and specify it as your callback function. The following is an example of a user-implemented callback function called msgCallback
. It processes the error message information available in the Msg
parameter that is contained within the BGMsgEventArgs
structure.
static void msgCallback(object sender, BGMsgEventArgs args) { Console.WriteLine("Time: " + dt2str(args.Msg.Time)); Console.WriteLine("Type " + args.Msg.Type); Console.WriteLine("Id " + args.Msg.Id); if (args.Msg.Text != NULL) Console.WriteLine("Text " + args.Msg.Text); if (args.Msg.Cause != NULL) Console.WriteLine("Cause " + args.Msg.Cause); Console.WriteLine(); }
The following event adds or removes a custom message handler to the Sync Agent.
public event BGMessageHandler MessageReceived
With the MessageReceived
event, you can add the message handler as follows:
sess.MessageReceived += new BGMessageHandler(msgCallback);
Sync calls the msgCallback
method with a message to report the current state and any errors for the Sync Agent or automatic synchronization. Within the msgCallback
method, you can perform the appropriate action for the errors returned in the Msg
variable of type BGMessage
, which is a public variable in the BGMsgEventArgs
structure. In addition, System.EventArgs
is the base class for BGMsgEventArgs
, which contains event data.
For a complete description of the BGMsgEventArgs
class, see Section 3.2.1.3.8, "BGMsgEventArgs Class".
The BGMessageType
enumeration contains the definitions for the different message types.
public enum BGMessageType { Info, Warning, Error }
Table 3-84 provides more details about these message types.
The BGMsgEventArgs
class contains the event arguments for the BGMessageHandler
interface. This class encapsulates the BGMessage
object. Both classes exist in the Oracle.OpenSync.SyncAgent
namespace.
public class BGMsgEventArgs : EventArgs { public readonly BGMessage Msg; }
The BGMessage
class contains error message information passed to handlers when an event occurs within the application.
Table 3-85 BGMessage Class Public Fields
Name | Description |
---|---|
|
Message creation time. |
|
Message type: |
|
Error message number. The error code can be one of the |
|
Message text. |
|
For error messages, optional cause of the error, which can be |
The BGException
class signals an error during execution of .Net Sync Agent Control API. The errors can be recoverable. In addition, the BGException
class can appear in the Cause
field in a BGMessage
object.
The BGException
class inherits from OSEException
, which is documented in Section 3.1.1.3.7, "OSEException Class".
The BGException
read-only properties are listed in Table 3-86.
Table 3-86 BGException Properties
Parameters | Description |
---|---|
|
Gets the exception error code. The error code can be one of the |
|
Gets the exception type name. |
|
Use the |
BGException(int errCode)
BGException(int errCode, string msg)
The parameters for the constructor are listed in Table 3-87:
Table 3-87 BGException Constructor Parameter Description
Parameter | Description |
---|---|
|
The error code can be one of the |
|
The error message. |
The following sections describe how to start/stop or enable/disable automatic synchronization from the OCAPI Sync Control API for the mobile client:
Section 3.2.1.4.1, "C/C++ Sync Control APIs to Start or Enable Automatic Synchronization"
Section 3.2.1.4.2, "Java Sync Control APIs to Start or Enable Automatic Synchronization"
Each of these APIs includes a stop method that has a timeout input parameter. You can supply one of the following values for the timeout, which is a long that specifies a time in milliseconds to wait for any current activity in the automatic synchronization to complete.
BG_STOP_TIMEOUT
: A value in seconds that allows the automatic synchronization process to complete before stopping the service. By default, this is set to 5 seconds.
BG_KILL_AGENT
: A value of -1 that makes the automatic synchronization service stop immediately, even if it is in the middle of a synchronization. If an automatic synchronization is in process, it will be terminated. NO errors or messages are returned.
Any long value in milliseconds: If the automatic synchronization does not stop within the time designated, the method returns with an error of BG_ERROR_TIMEOUT
. At this point, reissue the stop method to terminate the automatic synchronization immediately by supplying BG_KILL_AGENT
or -1 as the input value.
The following sections describe the Sync Control APIs for C/C++ applications.
To start or stop the Sync Agent, use the following APIs:
olError olStartSyncAgent() ; olError olStopSyncAgent(long timeout);
To enable or disable the Sync Agent, use the following APIs:
typedef struct _olSyncOpt { olBool bDisable; } olSyncOpt; olError olGetSyncOptions(olSyncOpt *opt); olError olSetSyncOptions(const olSyncOpt *opt);
The olGetSyncOptions
and olSetSyncOptions
methods take a pointer to the olSyncOpt
structure as a parameter. The olSyncOpt
structure contains the bDisable
boolean, which is true
if the Sync Agent is disabled.
To enable the Sync Agent, perform the following:
olSyncOpt opt.bDisable = FALSE; olSetSyncOptions(&opt);
To disable the Sync Agent, perform the following:
olSyncOpt opt.bDisable = TRUE; olSetSyncOptions(&opt);
Use olGetSyncOptions
method to retrieve the current value of the bDisable
boolean.
The following BGSyncControl
class has the following methods:
start
—Start automatic synchronization that was previously stopped.
stop
—Stop automatic synchronization. Normally, this is used to stop automatic synchronization before a manual synchronization is invoked. Then, use the start
method to restart automatic synchronization.
enable
—Enables automatic synchronization that was previously disabled.
disable
—Disables automatic synchronization on a client. Even if the client is restarted, automatic synchronization is not enabled unless you enable synchronization.
isEnabled
—Returns a boolean where true states that automatic synchronization is enabled.
package oracle.lite.msync; class BGSyncControl { public void start() throws SyncException; public void stop(long timeout) throws SyncException; void enable(); void disable(); bool isEnabled(); }
The following sections describe how to manage automatic synchronization through the Sync Agent and how to retrieve status of both the Sync Agent and any automatic synchronization events:
Note:
For more details on these classes, refer to the osync.js comments.Once automatic synchronization for the mobile client is enabled, you can manage it through the Sync Agent APIs. The Sync Agent controls and manages all aspects of automatic synchronization, which occurs in the background. If a manual synchronization is started, Sync Agent stops automatic synchronization as indicated and resumes the automatic synchronization activities when the manual synchronization finishes.
The JavaScript interface provides for the following functions:
Tracking the progress of the automatic synchronization process.
Retrieve the status of the Sync Agent.
The following are the classes and interface for the JavaScript API for controlling the Sync Agent and automatic synchronization:
BGSession Class
BGAgentStatus Class
BGSyncStatus Class
BGSession is the main class for controlling automatic synchronization through the Sync Agent, as follows:
Start, stop, pause, resume, enable or disable automatic synchronization.
Retrieve automatic synchronization status information.
Note:
There should be only a single BGSession object per your PhoneGap application.BGSession (success_cbk, error_cbk)
Table 3-88 BGException Constructor Parameter Description
Parameter | Description |
---|---|
|
A callback function that gets invoked upon successful API completion. |
|
An error callback function that gets invoked on any error in BGSession API. |
The public methods and their parameters for the BGSession class are listed in Table 3-89:
Table 3-89 BGSession Class Public Method Parameters
Method | Description |
---|---|
|
Returns TRUE if the Sync Agent is enabled; otherwise, FALSE. |
|
Closes the session and release all the resources used by the session. |
|
TRUE enables the Sync Agent; FALSE disables the Sync Agent. |
|
Retrieves the current Sync Agent status. See Section 3.2.1.5.3, "BGAgentStatus Object" for more details on the status information returned. |
int getAgentStatusCode () |
See Table 3-92 for more details on the status information returned. |
BGSyncStatus getSyncStatus() |
Gets current status of automatic synchronization managed by the Sync Agent. See Table 3-93 for more details on the status information returned. |
|
Pauses the Sync Agent.If the agent is aready paused or being paused, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be paused before returning. Use the waitForStatus method to wait for the Sync Agent. |
|
Resumes the Sync Agent. If the agent is already resumed or resuming, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be resumed before returning. Use the waitForStatus method to wait for the Sync Agent. |
|
Starts up the Sync Agent UI. |
|
Start the Sync Agent.If the agent is already running, starting, or resuming, this call is ignored. If the agent is paused, this call resumes the Sync Agent. This call is asynchronous and does not wait for the Sync Agent to be started before returning. Use the waitForStatus method to wait for the Sync Agent.Starts up the Sync Agent UI. |
|
Stop the Sync Agent.If the agent is already stopped or stopping, this call is ignored. This call is asynchronous, it does not wait for the Sync Agent to be stopped before returning. Use the waitForStatus method to wait for the Sync Agent. |
|
Wait for the Sync Agent to reach specified status. You can also wait for a specified timeout.
Returns TRUE if the agent has reached specified status; FALSE if the timeout has occurred. |
|
If sync agent is in DEFUNCT state, retrieve the error information that caused the bad internal state. See "Table 3-92, "Sync Agent Status Codes" for description of DEFUNCT. |
The following example demonstrates how to start the Sync Agent, retrieve status of the Sync Agent and add a message handler for the session:
// Create the BGSession object BGSession sess = new BGSession(onSuccess, onError); // Create an instance of BGAgentStatus var BGAgentStatusConst = new BGAgentStatus(); try { //Start the Sync Agent, which enables all automatic synchronization //events sess.start(); //Wait until the Sync Agent successfully starts sess.waitForStatus(BGAgentStatusConst.RUNNING); //Retrieve the status of the Sync Agent var s = sess.getAgentStatus(); //Print out the user that is using automatic synchronization console.log("User name: " + s.clientId); ... } finally { //When finished, close the session to release all resources sess.close(); }
The BGAgentStatus object represents the current status of the Sync Agent.
The methods for the BGAgentStatus are listed in Table 3-90:
Table 3-90 BGAgentStatus Class Public Method
Method | Description |
---|---|
|
Get language-specific name of a given status code. When you provide one of the status codes shown in Table 3-92, "Sync Agent Status Codes", the appropriate name is returned. Translation is dependent on the device language settings. |
BGAgentStatus provides status information on the Sync Agent. Table 3-91, "BGAgentStatus Class Fields" lists and describes the status information fields within the BGAgentStatus class.
Table 3-91 BGAgentStatus Class Fields
Parameter | Description |
---|---|
|
The name of the application or process that is executing the Sync Agent. |
|
Remaining percentage of battery life, if relevant. |
|
Sync user name. |
|
Name of the network currently used for synchronization, evaluated by Sync Agent. |
|
Network bandwidth in bits per second. |
int processId |
Process id of the process that is executing the Sync Agent, if relevant for a given platform. |
|
Retrieves the status of the Sync Agent. Status codes that can be returned are detailed in Table 3-92, "Sync Agent Status Codes". |
The BGAgentStatus object defines the Sync Agent status codes, which are as follows:
Table 3-92 Sync Agent Status Codes
Status Code | Status Name | Description |
---|---|---|
0 |
|
Sync Agent application is not running. |
1 |
|
Sync Agent is in the process of starting. |
2 |
|
Sync Agent is running. Any tasks within Sync Agent such as synchronization, compose, apply, rule evaluation, network evaluation and other operations can be active. |
3 |
|
Sync Agent is in the process of being paused. |
4 |
|
Sync Agent is paused. When paused, none of the tasks within Sync Agent are running. However, resources such as memory and threads, are saved in the case of a speedy resume. Pause and resume are generally faster than start and stop. When a manual synchronization is started, this pauses the Sync Agent until the manual synchronization is completed. At that point, the Sync Agent is resumed. |
5 |
|
Sync Agent is in the process of resuming. |
6 |
|
Sync Agent is in the process of stopping. |
7 |
|
Sync Agent encountered fatal error and is in a bad internal state. Sync Agent's environment needs to be cleaned up and restarted. |
The following provides an example of retrieving and processing the Sync Agent status:
/* retrieve the Sync Agent status */ var bgStatus = bgSess.getAgentStatus(); /* Print Sync Agent status */ console.log("Agent Status: " + BGAgentStatus.statusName(bgStatus.statusCode)); /* If agent is stopped, return */ if (bgStatus.statusCode == BGAgentStatusConst.STOPPED) return; /* Identify the client id, process id and name */ console.log("Client ID: " + bgStatus.clientId); console.log("Process Name: " + bgStatus.appName); console.log("Process ID: " + bgStatus.processId); /* network name and speed */ if (bgStatus .networkSpeed > 0) { console.log("Network Name: " + bgStatus.networkName); console.log("Network Speed: " + bgStatus.networkSpeed + " bps"); } else console.log("Network is not present"); /* battery power */ if (bgStatus.batteryPower > 0) console.log("Battery Power: " + bgStatus.batteryPower + "%"); else console.log("Battery is not present");
The current status of automatic synchronization is if automatic synchronization is in progress, startTime will have a non-zero value and endTime will be zero.
BGSyncStatus provides status information on automatic synchronization in the fields listed in Table 3-93, "BGSyncStatus Class Fields":
Table 3-93 BGSyncStatus Class Fields
Parameters | Description |
---|---|
|
End time of the last synchronization in milliseconds since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronzation is currently in progress or has not yet run. |
|
Exception message string thrown during the last synchronization. Returns NULL if the last synchronization was successful or no synchronization has completed yet. |
|
Priority of the current or last synchronization. |
|
Progress stage of synchronization if it is in progress. |
|
Progress value in percentage of synchronization, if it is in progress. |
|
Comma-separated names of publications synchronized currently or during last synchronization. |
|
Start time of current or last synchronization, in milliseconds, since the standard base time of January 1, 1970, 00:00:00 GMT. Returns zero if the synchronization has not yet started or the last synchronization time is unknown. |
The following provides an example of retrieving and processing the synchronization status:
/* Retrieve the synchronization status */ var bgSyncStatus = bgSess.getSyncStatus(); /* start time */ if (bgSyncStatus.startTime == 0) return; console.log("Sync Started: " + time2str(bgSyncStatus.startTime)); /* end time */ if (bgSyncStatus.endTime != 0) console.log("Sync Finished: " + time2str(bgSyncStatus.endTime)); /* publications synchronized */ console.log(”Publications: ” + bgSyncStatus.pubs); /* synchronization priority */ console.log("Sync Priority: " + (bgSyncStatus.prio == oseSession.PRIO_HIGH ? "High" : "Normal"));
Note:
The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.If you want to know at what stage the automatic synchronization cycle is, you can request status from the Sync Agent. In the client application, execute the get status API, which will return immediately with at what stage the automatic synchronization cycle is executing. This is different from the notification message API, which only returns when an event is completed within the synchronization cycle.
The get status API returns a structure that describes this event.
The following sections provide implementation details for each development language:
Section 3.2.2.1, "Retrieving Status for Automatic Synchronization in Java Applications"
Section 3.2.2.2, "Retrieving Status for Automatic Synchronization in C and C++ Applications"
Section 3.2.2.3, "Fields of the Automatic Synchronization Status Structure"
Use the getStatus
method in your Java client application to retrieve status on the automatic synchronization, as follows:
public BGSyncStatus getStatus() throws SyncException
This method returns the BGSyncStatus
class with the status information on the automatic synchronization, as follows:
public class BGSyncStatus { public String clientId; public short syncState; public String syncStateStr; public short syncProgress; public short lastSyncError; public short lastSyncType; public Date lastSyncTime; public short applyState; public String applyStateStr; public short applyProgress; public short lastApplyError; public Date lastApplyTime; public String networkName; public int networkSpeed; public int batteryPower; }
See Section 3.2.2.3, "Fields of the Automatic Synchronization Status Structure" for a description of the input parameters in the structure.
Use the olGetSyncStatus
method in your C/C++ client application to retrieve status on the automatic synchronization, as follows:
olError olGetSyncStatus(olSyncStatus *s);
The Sync Agent returns the olSyncStatus
class, which you provide as an input parameter, with the information on what happened, as follows:
typedef struct _olSyncStatus { char clientId[BG_MAX_USERNAME]; ol2B syncState; ol2B syncProgress; char syncStateStr[BG_MAX_STATUS_STR]; olError lastSyncError; ol2B lastSyncType; ol8B lastSyncTime; ol2B applyState; ol2B applyProgress; char applyStateStr[BG_MAX_STATUS_STR]; olError lastApplyError; olU2B _reserved; ol8B lastApplyTime; char networkName[BG_MAX_STATUS_STR]; ol4B networkSpeed; ol4B batteryPower; } olSyncStatus;
See Section 3.2.2.3, "Fields of the Automatic Synchronization Status Structure" for a description of the input parameters in the structure.
The status structure/class have the following fields:
Table 3-94 Status Class Fields
Field | Description |
---|---|
|
User name |
|
A numeric value that denotes the current synchronization stage, such as compose, send, or receive. |
|
String describing the state, as denoted in the |
|
A percentage that indicates the current progress for the automatic synchronization. |
|
If an error occurred in the last synchronization, this is the error code. If no error, this value is zero. |
|
The priority of the data for the last synchronization. If 1, then high priority data; if 0, then regular priority data was synchronized. |
|
Time of the last automatic synchronization. |
|
Code that indicates the state for the apply phase. |
|
String describing the state for the apply phase, as denoted in the |
|
A percentage that indicates the current progress for the apply phase. |
|
If an error occurred in the last apply phase, this is the error code. If no error, this value is zero. |
|
Time of the last apply phase. |
|
The network name assigned to this network. |
|
Current bandwidth of the network. |
|
Current battery power percentage. |
Note:
The following OCAPI APIs are currently supported for the mobile client, but are not the direction recommended for future applications. To develop applications for future support, migrate existing applications to use the OSE APIs for Managing Automatic Synchronization.You can develop a mobile client application to be notified when an automatic synchronization cycle occurs. The application is notified from the Sync Agent when the automatic synchronization completes as well as when a critical event occurs in the client device. For example, when the device battery runs critically low, Oracle Database Mobile Server can notify the application.
In the client application, create a procedure that executes one of the following message APIs. When your application calls the get message API, it blocks until an event occurs within an automatic synchronization. It returns a structure that describes this event.
The following sections provide implementation details for each development language:
Section 3.2.3.1, "Automatic Synchronization Notification for C/C++ Application"
Section 3.2.3.2, "Automatic Synchronization Notification for Java Applications"
Section 3.2.3.3, "Fields of the Automatic Synchronization Message Structure"
Use the olGetSyncMsg
method in your client application to receive the automatic synchronization notification when implementing for C/C++ applications. In order to block for the status, you need to perform the following:
Start the application messaging service with the olStartSyncMsg
method, providing a queue handle of type olAppMsgQ
. This message starts the messaging service and returns the queue handle in the olAppMsgQ
.
Execute the olGetSyncMsg
with the olAppMsgQ
message handle and the defined olSyncMsg
structure for the returned automatic synchronization information.
The following provides the method definitions:
typedef void *olAppMsgQ /* start application messaging, get queue handle */ olError olStartSyncMsg(olAppMsgQ *q); /*Provide the queue handle and block to retrieve automatic synchronization event */ olError olGetSyncMsg(olAppMsgQ q, olSyncMsg *m);
The olGetSyncMsg
method blocks until an event occurs, then the Sync Agent returns the olSyncMsg
class, which you provide as an input parameter, with the information on what happened, as follows:
typedef struct _olSyncMsg { ol2B type; ol2B id; char msg[BG_MAX_MSG]; } olSyncMsg;
See Section 3.2.3.3, "Fields of the Automatic Synchronization Message Structure" for a description of the input parameters in the structure.
The C/C++ application performs in a different manner than the Java and C# versions in that this creates a message service with its own message queue. Thus, when finished you must perform some cleanup to ensure that the message queue handle is released. Use the olStopSyncMsg
method to stop the messaging service and release the handle. This must be performed for every message queue that is opened with the olStartSyncMsg
method.
olError olStopSyncMsg(olAppMsgQ q);
If you want to force an existing olGetSyncMsg
to return, use the olCancelSyncMsg
from another thread in the application. This causes the olGetSyncMsg
to return with the BG_ERR_APP_MSG_CANCEL
error.
olError olCancelSyncMsg(olAppMsgQ q);
Use the getMessage
method in your client application to receive the automatic synchronization notification when implementing for Java applications, as follows:
public class BGSyncControl { public BGSyncMsg getMessage() throws SyncException; }
This method blocks until an event occurs, then the Sync Agent returns the BGSyncMsg
class with the information on what happened, as follows:
public class BGSyncMsg{ public int type; public int id; public String msg; }
See Section 3.2.3.3, "Fields of the Automatic Synchronization Message Structure" for a description of the input parameters in the class.
The message structure/class has the following fields:
Table 3-95 The Sync Message Variables
Variable | Description |
---|---|
Event type |
The event can be of three types, each of which indicate the level of severity of this notification:
|
Event identifier for |
The INFO event identifer describes what occurred, as follows:
|
Event identifier for the |
The
|
Event identifier for the |
The
|
Event Message |
String message that expounds on the information provided by the event type and identifier. |